java设计模式-工厂模式

工厂模式概念

   之前写过简单工厂模式(也称静态工厂模式),但是它不属于23中设计模式之一,并且它也违背了“开闭原则”,因此就有了它的升级版工厂模式,它也是属于创建型模式,维基百科上对它的定义是这样的:工厂方法模式的实质是“定义一个创建对象的接口,但让实现这个接口的类来决定实例化哪个类,工厂方法让类的实例化推迟到子类中进行。”并且它不像简单工厂模式那样,所有对象实例的创建都交给一个大工厂去完成(导致对单一职责的违背),工厂模式是将工厂职责单一化,每个工厂只针对一个对象创建,因此当要新增新的对象时,只需要增加对象类和与之对应的工厂类就可以,不必去修改原有的代码。


工厂模式类图

这里写图片描述
衣服的款式有儿童、青年、中年等,它们都有各自的制造工厂来制造它们
说明:
1. InstanceFactory代表创建对象实例工厂接口
2. ChildrenClothesFactory、YouthClothesFactory、MiddleAgeClothesFactory是具体的工厂类,实现InstanceFactory接口
3. Clothes是衣服接口
4. ChildrenClothes、YouthClothes、MiddleAgeClothes是具体款式衣服,现实Clothes接口


工厂模式实现

主体代码如下:

public interface InstanceFactory {
    public Clothes createInstance();
}
public class ChildrenClothesFactory implements InstanceFactory{
    @Override
    public Clothes createInstance() {
        return new ChildrenClothes();
    }
}
public 
class YouthClothesFactory implements InstanceFactory{
    @Override
    public Clothes createInstance() {
        return new YouthClothes();
    }
}
public class MiddleAgeClothesFactory implements InstanceFactory{
    @Override
    public Clothes createInstance() {
        return new MiddleAgeClothes();
    }
}
public interface Clothes{
    public void applyFor();
}
public class ChildrenClothes implements Clothes{

    @Override
    public void applyFor() {
        System.out.println("儿童穿的衣服");
    }
}
public class YouthClothes implements Clothes{

    @Override
    public void applyFor() {
        System.out.println("青年穿的衣服");
    }
}
public class MiddleAgeClothes implements Clothes{
    @Override
    public void applyFor() {
        System.out.println("中年穿的衣服");
    }
}

测试类代码:

public class DesignPatternTest {
    @Test
    public void factoryPatternTest(){
        InstanceFactory childrenClothesFactory = new ChildrenClothesFactory();
        Clothes childrenClosthes = childrenClothesFactory.createInstance();
        childrenClosthes.applyFor();

        InstanceFactory youthClothesFactory = new YouthClothesFactory();
        Clothes youthClosthes = youthClothesFactory.createInstance();
        youthClosthes.applyFor();

        InstanceFactory middleAgeClothesFactory = new MiddleAgeClothesFactory();
        Clothes middleAgeClosthes = middleAgeClothesFactory.createInstance();
        middleAgeClosthes.applyFor();
    }

}

输出如下:
这里写图片描述


工厂模式优缺点

  • 优点:相对简单工厂来说,遵循了“开闭原则”和“单一职责”。对客户端隐藏了对象实例化细节,客户端只需要告诉它们的需求,具体的实例化工作由对应的工厂来执行,和客户端需求不相干的工厂毫无关系。并且当需要在增加一种老年款式时,只需要增加对应的类和工厂即可,不必修改原有代码。
  • 缺点:代码的增加是成对增长的

                                                               -_-没有天才,只有勤奋的天才
    
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章