• 建造者模式


    一、定义:建造者模式(builder):将一个复杂的对象构建与它的表示分离,使得同样的构建过程可以创建不同的表示。

    二、示例代码:

    /*产品类*/
    public class Product {
        private List<String> parts = new ArrayList<String>();
    
        public void addPart(String part) {
            parts.add(part);
        }
    
        public void show() {
            for (String part : parts
            ) {
                System.out.println("产品建造过程");
                System.out.println("装配:" + part);
            }
        }
    }
    
    /*抽象建造者类*/
    public abstract class Builder {
        public abstract void builderA();
    
        public abstract void builderB();
    
        public abstract Product getResult();
    }
    
    
    /*具体建造类*/
    public class ConcreteBuilderA extends Builder {
        private Product product = new Product();
    
        @Override
        public void builderA() {
            product.addPart("part a");
        }
    
        @Override
        public void builderB() {
            product.addPart("part b");
        }
    
        @Override
        public Product getResult() {
            return product;
        }
    }
    
    /*具体建造类*/
    public class ConcreteBuilderB extends Builder {
        private Product product = new Product();
    
        @Override
        public void builderA() {
            product.addPart("part w");
        }
    
        @Override
        public void builderB() {
            product.addPart("part q");
        }
    
        @Override
        public Product getResult() {
            return product;
        }
    }
    
    
    /*指挥者类*/
    public class Director {
        public void Constructor(Builder builder) {
            builder.builderA();
            builder.builderB();
        }
    }
    
    
    /*客户端类*/
    public class Client {
        public static void main(String[] args) {
            Director director = new Director();
            Builder builder = new ConcreteBuilderA();
            director.Constructor(builder);
            Product product = builder.getResult();
            product.show();
        }
    }
    
    
  • 相关阅读:
    绿色版 notepad++ 添加鼠标右键菜单
    Scala 安装与配置
    Scala 神奇的下划线 _
    Kafka 安装部署
    Pulsar 下一代消息平台
    Sqoop 安装部署
    Flume 常用配置项
    Android-selector
    android- 9patch
    有关内存的思考题
  • 原文地址:https://www.cnblogs.com/yfy-/p/12026766.html
Copyright © 2020-2023  润新知