抽象工厂模式:解决了工厂模式的弊端,当新加一个功能的时候,不会影响之前的代码。
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package Factory; /** * * @author dev */ public interface IMobile { public void printName(); }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package Factory; /** * * @author dev */ public class IPhoneMobile implements IMobile { @Override public void printName() { System.out.println("我是一个iPhone手机!"); } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package Factory; /** * * @author dev */ public class SamsungMobile implements IMobile { @Override public void printName() { System.out.println("我是一个三星手机!"); } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package Factory; /** * * @author dev */ public interface IFactory { public IMobile produce(); }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package Factory; /** * * @author dev */ public class IPhoneFactory implements IFactory { @Override public IMobile produce() { return new IPhoneMobile(); } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package Factory; /** * * @author dev */ public class SamsungMobile implements IMobile { @Override public void printName() { System.out.println("我是一个三星手机!"); } }
public static void main(String[] args) { // TODO code application logic here IFactory factory = new IPhoneFactory(); IMobile iphone = factory.produce(); iphone.printName(); }