设计模式之 抽象工厂模式

工厂模式针对单个维度进行分类,抽象工厂模式针对多个维度进行分类。

 

示例

设计模式之 抽象工厂模式

(1)第1类产品接口及实现类的定义

public interface Phone{
    String call();
}

public class PhoneApple implements Phone{
    @Override
    public String call(){
        return "call somebody by apple phone";
    }
}

public class PhoneHuawei implements Phone{
    @Override
    public String call(){
        return "call somebody by huawei phone";
    }
}

(2)第2类产品接口及实现类的定义

public interface Computer{
    String internet();
}

public class ComputerApple implements Computer{
    @Override
    public String internet(){
        return "surf the internet by apple computer";
    }
}

public class ComputerHuawei implements Computer{
    @Override
    public String internet(){
        return "surf the internet by huawei computer";
    }
}

(3)工厂定义

public abstract class AbstractFactory{
    public abstract Phone createPhone(String brand);
    public abstract Computer createComputer(String brand);
}

public class PhoneFactory extends AbstractFactory{
    @Override
    public Phone createPhone(String brand){
        if("huawei".equals(brand)){
            return new PhoneHuawei();
        }else if("apple".equals(brand)){
            return new PhoneApple();
        }else{
            return null;
        }
    }
    
    @Override
    public Computer createComputer(String brand){
        return null;
    }
}

public class ComputerFactory extends AbstractFactory{
    @Override
    public Phone createPhone(String brand){
        return null;
    }
    
    @Override
    public Computer createComputer(String brand){
        if("huawei".equals(brand)){
            return new ComputerHuawei();
        }else if("apple".equals(brand)){
            return new ComputerApple();
        }else{
            return null;
        }
    }
}

(4)使用抽象工厂

AbstractFactory phoneFactory = new PhoneFactory();
Phone phoneHuawei = phoneFactory.createPhone("huawei");
Phone phoneApple = phoneFactory.createPhone("apple");
logger.info(phoneHuawei.call());
logger.info(phoneApple.call());

AbstractFactory computerFactory = new ComputerFactory();
Computer computerHuawei = computerFactory.createComputer("huawei");
Computer computerApple = computerFactory.createComputer("apple");
logger.info(computerHuawei.internet());
logger.info(computerApple.internet());

 

 

 

 

 

 

 

 

 

 

 

 

 


设计模式之 抽象工厂模式

设计模式之 抽象工厂模式

上一篇:SIP (Session Initiation Protocol) 协议


下一篇:Windows漏洞利用技术总结