HeadFirst设计模式篇四:工厂模式
生活随笔
收集整理的這篇文章主要介紹了
HeadFirst设计模式篇四:工厂模式
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
2019獨角獸企業重金招聘Python工程師標準>>>
先說明:由于HeadFirst屬于國外翻譯過來,文中的例子過于難理解,這里根據設計模式之禪進行總結
問題引入:
女媧造人故事:
女媧利用八卦爐造了3種不同膚色的人,這里女媧作為cilent,八卦爐作為工廠,人類作為產品
設計類圖:
Human、BlackHuman、YelloHuman、WhiteHuman:
public interface Human {void getColor();void talk(); }3個具體子類代碼略。。AbstractHumanFactory
public abstract class AbstractHumanFactory {public abstract <T extends Human> T createHuman(Class<T> clazz); }HumanFactory
public class HumanFactory extends AbstractHumanFactory {@Overridepublic <T extends Human> T createHuman(Class<T> clazz) {Human human = null;try {human = clazz.newInstance();} catch (Exception e) {e.printStackTrace();}return (T)human;} }NvWa
public class NvWa {public static void main(String[] args) {AbstractHumanFactory factory = new HumanFactory();Human human = factory.createHuman(WhiteHuman.class);human.talk();} }工廠方法模式的擴展
1、縮小為簡單工廠模式
去掉AbstractHumanFactory類,同時將HumanFactory的方法修改為靜態方法。
2、升級為多個工廠
3、替代單例模式
public class Singleton {private Singleton(){} }public class SingletonFactory {private static Singleton singleton;static {Class clazz = singleton.getClass();try {Constructor<Singleton> constructor = clazz.getDeclaredConstructor();constructor.setAccessible(true);singleton = constructor.newInstance();} catch (Exception e) {e.printStackTrace();}}public static Singleton getSingleton(){return singleton;} }說明:關于這里講的工廠模式和Head First一書中將的有差別,HeadFirst一書中將的工廠模式是將創建實例延遲到子類去做,這里設計模式之禪這本書講的知識簡單模式?!
抽象工廠模式:
問題引入:
人應該還有性別。。于是將八卦爐分成了兩個,一個制造男性,一個制造女性。
抽象工廠模式的特點:
優點:它不關心對象是如何創建出來的,只需要知道工廠類是誰,創建出一個需要的對象。
缺點:對于產品族的擴展會變得非常困難,不像工廠模式,所有的工廠類都要修改。
轉載于:https://my.oschina.net/silence88/blog/988831
總結
以上是生活随笔為你收集整理的HeadFirst设计模式篇四:工厂模式的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 大东电报与雷格斯在全球部署宝利通高清系统
- 下一篇: zabbix的启动和关闭脚本