工厂模式,个人理解主要是用来管理复杂对象的创建的

 

示例:

设计模式之 工厂模式

具体实现:

(1)接口定义

public interface Phone{
    String brand();
}

(2)实现类

public class Iphone implements Phone{
    @Override
    public String brand(){
        return "this is a Apple phone";
    }
}

public class HuaWei implements Phone{
    @Override
    public String brand(){
        return "this is a huawei phone";
    }
}

(3)定义工厂类

public class Factory{
    public Phone createPhone(String phoneName){
        if("huawei".equals(phoneName)){
            return new HuaWei();
        }else if("Apple".equals(phoneName)){
            return new Iphone();
        }else{
            return null;
        }
    }
}

(4)使用

public void main(String[] args){
    Factory factory = new Factory();
    Phone huawei = factory.createPhone("huawei");
    Phone iphone = factory.createPhone("Apple");
    logger.info(huawei.brand());
    logger.info(iphone.brand());
}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 


设计模式之 工厂模式