Java工厂模式

12/12/2015来源:Java教程人气:792

工厂模式将一个接口下所有子类的实例化过程封装起来,从而增加了系统的扩展性,并且可以减少代码日后的维护量。

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();
    }

}