簡單工廠模式(Easy Factory Pattern):簡單&粗暴解析
阿新 • • 發佈:2018-11-10
1.前言
- 在之前的文章設計模式(Design pattern):簡單&粗暴解析中已經為大家深入淺出解析了
設計模式
的 七大原則、三大型別。 - 本文為大家解析三大型別中 建立型 裡其中的
簡單工廠模式
。 - 文章中例項 linhaojian的Github
2.目錄
3.含義
建立物件的一個類。
4.解決
“使用例項者”和“例項建立過程”解耦,讓使用者不需關心建立過程,在改變建立過程時,不影響使用者。
5.原理
通過 【工廠】 這個中介,把建立物件的過程進行封裝,使 “呼叫者” 與 “建立過程” 進行分離
。
5.1 簡單工廠模式結構
5.2 結構分析
Factory:負責生產產品,供呼叫者使用。
Product:負責抽象約定產品(規範產品功能)。
ProductA/B:具體產品的實現。
5.3 例項(生產印表機)
Product
public interface Printer {
public void brand();
}
ProductA
public class HTCPrinter implements Printer{
@Override
public void brand() {
System.out. print("這是HTC的印表機");
}
}
ProductB
public class SAMSUNGPrinter implements Printer{
@Override
public void brand() {
System.out.print("這是三星的印表機");
}
}
Factory
public class Factory {
public static Printer getPrinter(String brand){
if(brand==null){
return null;
}
if(brand.equalsIgnoreCase("SAMSUNG")){
return new SAMSUNGPrinter();
}else if(brand.equalsIgnoreCase("HTC")){
return new HTCPrinter();
}
return null;
}
}
6.優點
1.“使用者” 無需關心建立過程,便於建立過程修改的維護。
2.統一管理建立相同型別的物件,提高程式碼可讀性。
7.缺點
1.當新增新的物件時,需要修改工廠類,違反了“開閉原則”。
8.總結
- 到此,
簡單工廠模式
就解析完畢,後續我會把上述 三大型別模式 下的各子模式進行解析分享,
請繼續關注linhaojian_簡書! - 如果喜歡我的分享,可以點選 關注 或者 贊,你們支援是我分享的最大動力 。
- linhaojian的Github
歡迎關注linhaojian_CSDN部落格或者linhaojian_簡書!
不定期分享關於安卓開發的乾貨。
設計模式(Design pattern):簡單&粗暴解析
單例模式(Singleton Pattern):簡單&粗暴解析
簡單工廠模式(Easy Factory Pattern):簡單&粗暴解析
工廠模式(Factory Pattern):簡單&粗暴解析):簡單&粗暴解析
抽象工廠模式(Abstract Factory Pattern):簡單&粗暴解析
建造者模式(Builder Pattern):簡單&粗暴解析
寫技術文章初心
- 技術知識積累
- 技術知識鞏固
- 技術知識分享
- 技術知識交流