zoukankan      html  css  js  c++  java
  • 工厂方法模式(设计模式_08)

    工厂方法模式遵循了,开放封闭式原则,我们直接用案例来体现:

    // 定义一个电脑接口
    public interface IComputer {
    
        // 获取电脑组件的方法
        public void myStyle();
    
    }
    
    // 电脑适配器实现电脑接口
    public class Adapter implements IComputer{
    
        public void myStyle() {
            System.out.println("这是电脑的充电器....");
        }
    
    }
    
    // 电脑主板实现电脑
    public class Board implements IComputer {
    
        public void myStyle() {
            System.out.println("这是电脑主板...");
        }
    
    }
    
    // 显示屏类实现电脑
    public class Display implements IComputer{
    
        public void myStyle() {
            System.out.println("这是电脑显示屏...");
        }
    
    }
    

    此时切换到工厂方法模式区域

    // 定义工厂接口,此工厂接口可以制作很多东西,例如 电脑,平板,手机,等等....
    
    public interface IFactory {
    
        /**
         * 定义制造电脑的函数
         * @return 返回电脑接口
         */
        public IComputer getComputer();
    
    }
    
    // 工厂实现工厂接口
    public class Factory implements IFactory {
    
        public IComputer getComputer() {
            // 这个Computer类,下面区域有介绍到
            return new Computer(new Display(), new Board(), new Adapter());
        }
    
    }
    
    // Computer类
    // 电脑类实现电脑接口 == 一台电脑
    public class Computer implements IComputer{
    
        // public Computer(){};
    
        private Display engine;
        private Board underpan;
        private Adapter wheel;
    
        public Computer(Display engine, Board underpan, Adapter wheel){
            this.engine = engine;
            this.underpan = underpan;
            this.wheel = wheel;
        }
    
        public void myStyle() {
            engine.myStyle();
            underpan.myStyle();
            wheel.myStyle();
        }
    
    }
    
    // 客户端程序
    public class Main {
    
        public static void main(String [] args) {
    
            // 得到工厂
            IFactory factory = new Factory();
    
            // 调用工厂去制作电脑
            IComputer car = factory.getComputer();
    
            car.myStyle();
    
        }
    
    }

    运行结果:
    这里写图片描述


    谢谢大家的观看,更多精彩技术博客,会不断的更新,请大家访问,
    刘德利CSDN博客, http://blog.csdn.net/u011967006

  • 相关阅读:
    五、MapReduce 发布服务
    四、MapReduce 基础
    三、Hadoop 的 API
    二、HDFS 架构
    php身份证号的验证
    php性能优化
    PHP网站开发方案
    php一个不错的分页
    2013年最流行的php框架盘点
    程序员之路
  • 原文地址:https://www.cnblogs.com/android-deli/p/10322221.html
Copyright © 2011-2022 走看看