JAVA设计模式 - 简单工厂(Simple Factory)

简单工厂(Simple Factory)

在创建一个对象时不向客户暴露内部细节,并提供一个创建对象的通用接口。

1)我举个栗子,没有工厂的时候,我们想要一个苹果手机,我们需要自己new创建一个出来。(这时候我们想创建一个手机需要很多零件(参数),每当我们想要一个手机就要准备很多零件来创造一个手机,这就很麻烦了,那么有没有可以我想要手机就能拿到,不管它需要什么零件,这就是为什么工厂类的由来)

2)现在有了工厂模式,想要手机直接到工厂取就好了。(零件的思想我没有在案例中体现出来)


/**
 * 苹果系列
 */
public interface Apple {
    
    
}
public class Iphone12 implements Apple {
    
    
}
public class Iphone11 implements Apple {
    
    
}
public class Iphone10 implements Apple {
    
    
}

以下的 IphoneFactory 是简单工厂实现,它被所有需要进行实例化的客户类调用。

public class IphoneFactory {
    
    
    public static Product createIphone(int type) {
    
    
        switch (type) {
    
    
          case 12:
             return new Iphone12();
          case 11:
             return new Iphone11();
          default:
             return new Iphone10();
        }
    }
}

客户类:

public class Consumer {
    
    

    public static void main(String[] args) {
    
    
        Apple iphone12 = IphoneFactory.createIphone(12);
    }
}

简单工厂模式又称静态工厂方法模式。从命名就可以看出这个模式很简单,就是用一个类(工厂)来提供创建对象的接口。

猜你喜欢

转载自blog.csdn.net/weixin_43957211/article/details/110661737