簡單設計模式比較簡單,15分鐘的時間,跟着我作,十幾分鍾學會簡單設計模式,開始吧:java
1.使用new實例化一個對象時,你確定知道這種代碼缺乏彈性,綁定着具體的類會致使代碼更加脆弱,簡單工廠模式就是針對接口編程,巧妙的設計解決這個問題。apache
Pizza pizza =new CheesePizza();
2,直接上一個簡單工廠模式代碼,而後分析。你能夠拷貝本身創建如下四個類編程
Pizza類:披薩類設計模式
package com.example.demo.factory; import java.util.ArrayList; public abstract class Pizza { /** * 名稱 */ String name; /** * 麪糰類型 */ String dough; /** * 醬料 */ String sauce; /** * 做料 */ ArrayList<String> toppings = new ArrayList<String>(); void prepare() { System.out.println("準備 " + name); System.out.println("揉麪團..."); System.out.println("添加醬料..."); System.out.println("添加做料: "); for (int i = 0; i < toppings.size(); i++) { System.out.println(" " + toppings.get(i)); } } void bake() { System.out.println("烘烤25分鐘"); } void cut() { System.out.println("把Pizza對角切片"); } void box() { System.out.println("把Pizza裝盒子"); } public String getName() { return name; } }
簡單披薩工廠類:SimplePizzaFactory,根據需求建立不一樣的披薩eclipse
package com.example.demo.factory; import org.apache.commons.codec.binary.StringUtils; public class SimplePizzaFactory { public Pizza createPizza(String type) { Pizza pizza = null; if (StringUtils.equals(type,"cheese")) { pizza = new CheesePizza(); } else if (StringUtils.equals(type,"veggie")) { pizza = new VeggiePizza(); } return pizza; } }
披薩店類:PizzaStore,生成披薩ide
package com.example.demo.factory; public class PizzaStore { private final SimplePizzaFactory factory; public PizzaStore(SimplePizzaFactory factory) { this.factory = factory; } public Pizza orderPizza(String type) { Pizza pizza; pizza = factory.createPizza(type); pizza.prepare(); pizza.bake(); pizza.cut(); pizza.box(); return pizza; } }
main啓動類:this
package com.example.demo; import com.example.demo.factory.Pizza; import com.example.demo.factory.PizzaStore; import com.example.demo.factory.SimplePizzaFactory; public class PizzaApplication { public static void main(String[] args) { SimplePizzaFactory factory = new SimplePizzaFactory(); PizzaStore store = new PizzaStore(factory); Pizza pizza = store.orderPizza("cheese"); System.out.println("We ordered a " + pizza.getName() + "\n"); pizza = store.orderPizza("veggie"); System.out.println("We ordered a " + pizza.getName() + "\n"); } }
將這四個類考入到你的eclipse或者idea運行,恐怕不要過多解釋你就能看懂其中的巧妙之處,其實簡單工廠不是一個設計模式,反而更像一種編程習慣;idea
運行結果:spa
好了到這我想你拷貝代碼大概用了5分鐘,接下來十分鐘本身分析調用邏輯流程比較好,別人說永遠說不清楚,邏輯較爲簡單,梳理一下就行了,就不詳細講解,相信你能夠作到的,在這僅提供一份資源和信念;設計
代碼是我本身運行沒問題拷貝過來的,若有問題無法運行或者須要詳細講解的請留言,定當回覆一塊兒探討!謝謝!