不是工厂模式的简单工厂

简单工厂


    工厂模式属于创建型模式:用于描述“怎样创建对象”,一般分为工厂模式和抽象工厂。
    引入简单工厂模式,这种模式不属于工厂模式,但是为了便于理解后续的两种模式,便引入了这个概念,同时还有一个重要的思想----再暴露逻辑的前提下生成一个实例。

设想以下有如下这样的一个场景,当你想造一间房子的时候,你肯定需要门,但是自己一个一个造就太慢了,所以你打算去工厂购买木门,让工厂去造,而你只需要说出你需要的门的要求就好。

在这里插入图片描述
在产品的规范的定义上我们很简单的就想到了接口,接口其很重要的一个功能就是为了定义规范,在简单了解需求后我们就可以得出大概的思路。

interface Door{                    //通过接口来规范产品
    public float getWidth();
    public float getHeight();
}

class WoodenDoor implements Door{  //木门
    protected float width;
    protected float height;

    public  WoodenDoor(float width,float height) {
        this.width = width;
        this.height = height;
    }

    @Override
    public float getWidth() {
        System.out.println("获取木门的宽度");
        return width;
    }

    @Override
    public float getHeight() {
        System.out.println("获取木门的高度");
        return height;
    }
}

class IronWoodenDoor implements Door{     //铁门
    protected float width;
    protected float height;

    public  IronWoodenDoor(float width,float height) {
        this.width = width;
        this.height = height;
    }

    @Override
    public float getWidth() {
        System.out.println("获取铁门的宽度");
        return width;
    }

    @Override
    public float getHeight() {
        System.out.println("获取铁门的高度");
        return height;
    }
}


class DoorFactory{
    public static Door makerDoor(float width,float height,String type)                        //造门的工厂
    {
        if (type.equals("wood"))   //根据条件判断是顾客需要什么门
        {
            return new WoodenDoor(width,height);
        }
        else if (type.equals("iron"))
        {
            return new IronWoodenDoor(width,height);
        }
        else {
            return null;
        }
    }
}

//可以看出在对用户需求的门上用了if-else来判断,这段代码所书写的不是那么好
//那么接下来就引入的工厂模式和抽象工厂。

主方法如下:

 public static void main(String[] args) {
        DoorFactory doorfactory = new DoorFactory();
        Door wood1 = DoorFactory.makerDoor(20,100,"wood");
        System.out.println(wood1.getWidth());
        System.out.println(wood1.getHeight());
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值