Java設計模式之簡單工廠模式
阿新 • • 發佈:2018-12-10
工廠模式:就是我們最常用的例項化物件模式,是用工廠方法代替new操作的一種模式。
實現步驟:使用工廠物件,根據傳遞的引數建立物件
ex:
/** * 簡單工廠模式:就是建立一個工廠專門用來new物件 * @author 鄭清 */ public class TestFactory { public static void main(String[] args) { Phone newIntance = PhoneFactory.newIntance("IPhone"); newIntance.call();//iphone... Phone newIntance2 = PhoneFactory.newIntance("MIPhone"); newIntance2.call();//小米... } } class PhoneFactory { //工廠:用來生產手機 public static Phone newIntance(String name){ if(name.equals("IPhone")){ return new IPhone(); }else if(name.equals("MIPhone")){ return new MIPhone(); }else{ return null; } } } interface Phone { void call(); } class IPhone implements Phone { @Override public void call() { System.out.println("iphone..."); } } class MIPhone implements Phone { @Override public void call() { System.out.println("小米..."); } }
執行結果圖: