设计模式之 工厂模式

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

 

示例:

蜂蜜浏览器_微信图片_20210903100435

具体实现:

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

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 


posted @ 2021-09-03 11:07  yeren2046  阅读(26)  评论(0编辑  收藏  举报