设计模式之工厂模式2
在前一篇介绍简单工厂模式中大家大家知道,要产生具体水果对象就必须去FriutFactory这个类中产生。这个类是一个水果的工厂。这个水果本身就是一个抽象概念。随着具体水果的增加和丰富,可能要更改FriutFactory这个类就比较频繁。因此工厂设计模式就在简单工厂设计模式上进行再次的抽象。这次抽象将按照具体的水果来进行抽象。比如苹果,那么就设计一个苹果工厂类,这个苹果工厂类就专门用来产生苹果对象。而联系到现实时候中工作分工的细化是一样的道理。
下面直接看源码
//水果接口public interface Fruit {/* * 采集水果 */public void get();}//具体的水果苹果实现水果的接口public class Apple implements Fruit{public void get(){System.out.println("采集苹果");}}//具体的水果香蕉实现水果的接口public class Banana implements Fruit{public void get(){System.out.println("采集香蕉");}}//产生水果的工厂public interface FruitFactory {public Fruit getFruit();}//苹果类工厂,用于产生具体的苹果对象public class AppleFactory implements FruitFactory {public Fruit getFruit() {return new Apple();}}//香蕉类工厂,用于产生具体的香蕉对象public class BananaFactory implements FruitFactory {public Fruit getFruit() {return new Banana();}}
// 李子public class Pear implements Fruit {public void get() {System.out.println("采集李子");}}//产生李子对象的工厂,增加不影响和不改动之前的代码public class PearFactory implements FruitFactory {public Fruit getFruit() {return new Pear();}}
public class Client{public static void main(String[] args) {//实例化AppleFactoryFruitFactory ff = new AppleFactory();Fruit apple = ff.getFruit();apple.get();FruitFactory ff2 = new BananaFactory();Fruit banana = ff2.getFruit();banana.get();FruitFactory ff3 = new PearFactory();Fruit pear = ff3.getFruit();pear.get();}}