以購買電話卡為例說明 簡單工廠模式
public interface Card { public void buyTelCard(); }
public class MobileCard implements Card { @Override public void buyTelCard() { System.out.println("购买移动卡"); } }
public class UnicomCard implements Card { @Override public void buyTelCard() { System.out.println("购买联通卡"); } }
public class CardFactory { public Card buyCard(String styleName) { if (styleName.toLowerCase().equals("mobile")) { return new MobileCard(); } else if (styleName.toLowerCase().equals("unicom")) { return new UnicomCard(); } return null; } }/** * * 简单工厂模式(Simple Factory Pattern) * */ public class Test { public static void main(String[] args) { CardFactory factory=new CardFactory(); factory.buyCard("mobile").buyTelCard(); } }
更多java 設計模式之 簡單工廠模式相關文章請關注PHP中文網!