1.简单工厂模式(用的最多)
优点没:没必要知道那么多接口的实现了,只需要知道工厂,生成的对象我们只需要知道知道接口
缺点:不修改代码无法拓展实现类,拓展性较差
public interface Car { } public class Audi implements Car { } public class Bwm implements Car { } //简单工厂:可拓展性差,每增加一个车型,都需要在这其中加入else if public class CarFactory { public static Car createCar(String str) { if(str=="audi") { return new Audi(); }else if(str=="bwm") { return new Bwm(); } return null; } } public class Client { public static void main(String[] args) { System.out.println(CarFactory.createCar("audi")); } }
2.工厂方法模式
优点:较简单工厂可拓展性较好
缺点:较简单工厂需要知道的工厂较多,结构较简单工厂复杂,随着工厂类的增加,类越来越多
public interface Car { } public class Audi implements Car { } public class Bwm implements Car { } public interface Factory { } public class AudiFactory implements Factory{ public static Car createCar() { return new Audi(); } } public class BwmFactory implements Factory { public static Car createCar() { return new Bwm(); } } public class Client { public static void main(String[] args) { Car audi = AudiFactory.createCar(); } }
3.抽象工厂模式
优点:用来生产不同产品族的全部产品;支持增加产品族
缺点:对于增加新的产品,无能为力;支持增加产品族
public interface Engine { } public class LowEngine implements Engine{ } public class LuxuryEngine implements Engine{ } public interface Factory { } public class LowFactory implements Factory{ public static Engine createEngine() { return new LowEngine(); } } public class LuxuryFactory implements Factory{ public static Engine createEngine() { return new LuxuryEngine(); } }
原文:https://www.cnblogs.com/gg128/p/9550615.html