java 设计模式之 简单工厂模式(Simple Factory Pattern) 代码实现

306020 8年前
     以购买电话卡为例说明 简单工厂模式    <br />    <pre class="brush:java; toolbar: true; auto-links: false;">public interface Card {    public void buyTelCard();   }</pre>    <br />    <pre class="brush:java; toolbar: true; auto-links: false;">public class MobileCard implements Card {   @Override  public void buyTelCard() {   System.out.println("购买移动卡");  }  }</pre>    <pre class="brush:java; toolbar: true; auto-links: false;">public class UnicomCard implements Card {   @Override  public void buyTelCard() {   System.out.println("购买联通卡");  }  }</pre>    <pre class="brush:java; toolbar: true; auto-links: false;">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;  }  }<pre class="brush:java; toolbar: true; auto-links: false;">/**  *   *  简单工厂模式(Simple Factory Pattern)  *  */ public class Test {    public static void main(String[] args) {   CardFactory factory=new CardFactory();   factory.buyCard("mobile").buyTelCard();  } }</pre><br /> <br /> <br /> </pre>