• 设计模式之 抽象工厂模式


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

    示例

    image

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

  • 相关阅读:
    更易型算法(Manipulating Algorithms)
    迭代器之配接器
    Windows下BBv2安装编译libtorrent
    swfupload简单使用
    Openx 中文编码解决方案
    常见c语言编译错误解析(转)
    新建一个scrapy项目
    判断两个日期的时间部分之差
    javascript弹出子窗口并返回值
    转:浅析ASP.NET中页面传值的几种方法
  • 原文地址:https://www.cnblogs.com/betterwgo/p/15222437.html
Copyright © 2020-2023  润新知