设计模式工厂方法模式(Factory Method)
Posted ssslinppp
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了设计模式工厂方法模式(Factory Method)相关的知识,希望对你有一定的参考价值。
工厂方法模式
定义了一个创建对象的接口,但由子类决定要实现的类是哪一个。工厂方法让类把实例化推迟到子类。
所有的工厂模式都用来封装对象的创建。工厂方法模式通过让子类决定改创建的对象是什么,来达到将对象创建的过程封装的目的。
所有的工厂模式都用来封装对象的创建。工厂方法模式通过让子类决定改创建的对象是什么,来达到将对象创建的过程封装的目的。
工厂方法类图
![](https://image.cha138.com/20210612/ee8929a0ab204d86b9f09336d14fdfeb.jpg)
示例:Pizza工厂类图
以生产Pizza作为示例,下面是具体的工厂方法类图和实现的代码:
![](https://image.cha138.com/20210612/0c2bb441e5294eba9885b3d1885c39dc.jpg)
![](https://image.cha138.com/20210612/34242218b99848d5bc02eaf4e186b3a9.jpg)
![](https://image.cha138.com/20210612/6b64186db58e419596037521c748e14c.jpg)
![](https://image.cha138.com/20210612/14b738dc3ce8494a8ba1943c90b0ec95.jpg)
抽象产品类
![](https://image.cha138.com/20210612/ee1e299bd0534eefb922a2fe91958c32.jpg)
具体产品(类型A)
![](https://image.cha138.com/20210612/334958abf0e64269aa4a640308da84f0.jpg)
![](https://image.cha138.com/20210612/cc320277c7984b3e907768ccecdc78c9.jpg)
具体产品(类型B)
![](https://image.cha138.com/20210612/652bb80797dc40e5b3d1f162e33c17cc.jpg)
![](https://image.cha138.com/20210612/b34c794d46c8465ea2d504dbe066b805.jpg)
抽象工厂类
![](https://image.cha138.com/20210612/2ae69cfbe179466a95b51589e3d99888.jpg)
具体创建者(具体的工厂)
![](https://image.cha138.com/20210612/931ab88c010a433e840f9efca832d6ee.jpg)
![](https://image.cha138.com/20210612/1190ae94058e4e83bb05d11b10234011.jpg)
测试类和测试结果
![](https://image.cha138.com/20210612/4c2d29b968114e908793d73518d2ec10.jpg)
![](https://image.cha138.com/20210612/6886db20c3f34aadb8cdbbb9492c1c1a.jpg)
以上是关于设计模式工厂方法模式(Factory Method)的主要内容,如果未能解决你的问题,请参考以下文章