GOF设计模式之工厂模式(Factory)
实例化对象,用工厂方法代替new操作。
将选择实现类、创建对象统一管理和控制。从而将调用者跟我们的实现类解耦。
工厂模式之简单工厂模式
接口实现
1 | public interface Animal { |
继承接口实现方法
1 | public class Cat implements Animal{ |
工厂
1 | public class Animalfactory { |
测试
1 | /** |
GOF设计模式之工厂方法模式
接口实现
Animal接口
1 | public interface Animal { |
Creatfactory接口
1 | public interface Creatfactory { |
继承接口实现方法
继承Animal
1 | public class Cat implements Animal{ |
继承Creatfactory
1 | public class Catfactory implements Creatfactory{ |
测试
1 | /** |
GOF设计模式之抽象工厂模式
接口实现
Tyre接口
1 | public interface Tyre { |
Seat接口
1 | public interface Seat { |
Engine接口
1 | public interface Engine { |
CarFactory接口
1 | public interface CarFactory { |
继承接口实现方法
继承Tyre
1 | class LuxuryTyre implements Tyre{ |
继承Seat
1 | class LuxurySeat implements Seat{ |
继承Engine
1 | class LuxuryEngine implements Engine{ |
继承CarFactory
1 | class LuxuryCarFactory implements CarFactory{ |
测试
1 | public class Client { |
总结
·核心本质
– 实例化对象,用工厂方法代替new操作。
– 将选择实现类、创建对象统一管理和控制。从而将调用者跟我们的实现类解耦。
·工厂模式
– 简单工厂模式
·用来生产同一等级结构中的任意产品。(对于增加新的产品,需要修改已有代码)
– 工厂方法模式
·用来生产同一等级结构中的固定产品。(支持增加任意产品)
– 抽象工厂模式
·用来生产不同产品族的全部产品。(对于增加的新产品,无能为力:支持增加产品族)
·工厂模式要点
– 简单工厂模式(静态工厂模式)
·虽然某种程度不符合设计原则,但实际应用最多。
– 工厂方法模式
·不修改已有类的前提下,通过增加新的工厂类实现扩展。
– 抽象工厂模式
·不可以增加产品,可以增加产品族。