Java工厂模式
工厂模式将一个接口下所有子类的实例化过程封装起来,从而增加了系统的扩展性,并且可以减少代码日后的维护量。
interface IPlug{ void start(); } class TV implements IPlug{ public void start(){ System.out.println("TV start"); } } class AirCon implements IPlug{ public void start(){ System.out.println("AirCon start"); } } class Factory{ public static IPlug getInstance(String className){ if("TV".equals(className)){ return new TV(); } else if("AirCon".equals(className)){ return new AirCon(); } else { return null; } } } public class factoryDemo { public static void main(String[] args) { // TODO Auto-generated method stub IPlug ip = Factory.getInstance("TV"); ip.start(); ip = Factory.getInstance("AirCon"); ip.start(); } }