设计模式-5种创建型

Tags
#设计模式

1.单例模式

  1. 饿汉式
  1. 懒汉式
  1. 双重锁定式
  1. 枚举式
  1. 静态内部类式
此处仅以最常见的双重锁定式为例! 适用于内存中只有唯一实例,避免频繁创建销毁。 注意:易导致内存泄露!不利于mock测试!
代码
package base.designpattern.creational;

/**
 * 单例模式
 * <p>
 * 案例:臣子觐见皇帝
 * Created by yutianran on 16/7/1.
 */
public class SingletonPattern {

    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            //每次都有一个臣子觐见皇帝
            Emperor emperor = Emperor.getInstance();
            Minister minister = new Minister();
            minister.see(emperor);
        }
    }

    //皇帝
    public static class Emperor {
        private static Emperor instance;

        //禁止外部创建
        private Emperor() {
        }

        //双重锁定式
        public static Emperor getInstance() {
            if (null == instance) {
                synchronized (Emperor.class) {
                    if (null == instance) {
                        instance = new Emperor();
                    }
                }
            }
            return instance;
        }
    }

    //臣子
    public static class Minister {

        public void see(Emperor emperor) {
            System.out.println("臣子:" + this + "\t觐见皇帝:" + emperor);
        }
    }
}
输出:
MyAttachment/05-Attachment/1458573-c9c2e8e4a1431a2e.png

2.原型模式

代码:
package base.designpattern.creational;


/**
 * 原型模式
 * <p>
 * 案例:盗版书
 * Created by yutianran on 16/7/1.
 */
public class PrototypePattern {

    public static void main(String[] args) {
        //正版书
        Book src = new Book("设计模式之禅");
        src.setPreface(new Preface("这是一本介绍设计模式的书"));

        //盗版书
        Book pirate = src.clone();
        //修改书名
        pirate.setName("设计模式之禅-Clone");
        //修改序言
        Preface preface = pirate.getPreface();
        preface.setDesc("这是一本介绍设计模式的书-Clone");

        System.out.println("正版书:" + src.toString());
        System.out.println("盗版书:" + pirate.toString());
    }

    //书
    public static class Book implements Cloneable {
        private String name;//书名
        private Preface preface;//序言

        public Book(String name) {
            this.name = name;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public Preface getPreface() {
            return preface;
        }

        public void setPreface(Preface preface) {
            this.preface = preface;
        }


        @Override
        protected Book clone() {
            Book clone = null;
            try {
                clone = (Book) super.clone();
                //这里必须同时调用引用对象的clone方法
                clone.preface = this.preface.clone();
            } catch (CloneNotSupportedException e) {
                System.out.println("克隆出错:" + e.getMessage());
            }
            return clone;
        }

        @Override
        public String toString() {
            return "Book{" +
                    "name='" + name + '\'' +
                    ", preface=" + preface +
                    '}';
        }
    }

    //序言
    public static class Preface implements Cloneable {
        private String desc;//介绍

        public Preface(String desc) {
            this.desc = desc;
        }

        public String getDesc() {
          
输出:
MyAttachment/05-Attachment/1458573-9b4f8e430943da73.png

3.建造者模式

代码:
package base.designpattern.creational;

/**
 * 建造者模式
 * <p>
 * 案例:创建网络请求
 * Created by yutianran on 16/7/1.
 */
public class BuilderPattern {

    public static void main(String[] args) {
        String url = "http://baidu.com";
        Request request = new Request.Builder()
                .url(url)
                .method("POST")
                .headers("Content-Type:application/json;charset=UTF-8")
                .body("{\"userId\":145}")
                .tag(url)
                .build();
        System.out.println("网络请求:" + request.toString());
    }

    //网络请求类
    public static class Request {
        private String url;
        private String method;
        private String headers;
        private String body;
        private String tag;

        public Request(Builder builder) {
            if (null == builder.url) {
                throw new IllegalArgumentException("url == null");
            }
            this.url = builder.url;
            this.method = builder.method;
            this.headers = builder.headers;
            this.body = builder.body;
            this.tag = builder.tag;
        }

        public String getUrl() {
            return url;
        }

        public String getMethod() {
            return method;
        }

        public String getHeaders() {
            return headers;
        }

        public String getBody() {
            return body;
        }

        public String getTag() {
            return tag;
        }

        @Override
        public String toString() {
            return "Request{" +
                    "url='" + url + '\'' +
                    ", methodB='" + method + '\'' +
                    ", headers='" + headers + '\'' +
                    ", body='" + body + '\'' +
                    ", tag='" + tag + '\'' +
                    '}';
        }

        //建造者
        public static class Builder {
            private String url;
            private String method;
            private String headers
输出:
MyAttachment/05-Attachment/1458573-38f8e3a9733459b4.png

4.静态工厂模式

代码:
package base.designpattern.creational;

/**
 * 简单工厂模式
 * <p>
 * Created by yutianran on 16/7/1.
 */
public class SimpleFactoryPattern {

    public static void main(String args[]) {
        IProduct product = SimpleFactory.produce(ProductA.class);
        product.method();
    }

    //抽象产品
    public static abstract class IProduct {
        public abstract void method();
    }

    //具体产品A
    public static class ProductA extends IProduct {
        @Override
        public void method() {
            System.out.println("I'm ProductA!");
        }
    }

    //具体产品B
    public static class ProductB extends IProduct {
        @Override
        public void method() {
            System.out.println("I'm ProductB!");
        }
    }

    //静态工厂
    public static class SimpleFactory {

        public static <T extends IProduct> T produce(Class<T> clazz) {
            IProduct human = null;
            try {
                human = (IProduct) Class.forName(clazz.getName()).newInstance();
            } catch (Exception e) {
                System.out.println("创建错误:" + e.getMessage());
            }
            return (T) human;
        }
    }


}

输出:
MyAttachment/05-Attachment/1458573-693b2be77447148b.png

5.工厂方法模式

代码:
package base.designpattern.creational;

/**
 * 工厂方法模式
 * <p>
 * Created by yutianran on 16/7/1.
 */
public class FactoryMethodPattern {

    public static void main(String[] args) {
        AbstractFactory factoryA = new ConcreteFactoryA();
        AbstractProduct product = factoryA.produce();
        product.method();
    }

    //抽象产品
    public static abstract class AbstractProduct {
        public abstract void method();
    }

    //抽象工厂
    public static abstract class AbstractFactory {
        public abstract AbstractProduct produce();
    }


    //具体产品
    public static class ProductA extends AbstractProduct {
        @Override
        public void method() {
            System.out.println("I'm ProductA!");
        }
    }

    public static class ProductB extends AbstractProduct {
        @Override
        public void method() {
            System.out.println("I'm ProductB!");
        }
    }

    //具体工厂
    public static class ConcreteFactoryA extends AbstractFactory {
        @Override
        public ProductA produce() {
            return new ProductA();
        }
    }

    public static class ConcreteFactoryB extends AbstractFactory {
        @Override
        public ProductB produce() {
            return new ProductB();
        }
    }


}
输出:
MyAttachment/05-Attachment/1458573-04ad25a37f7b22fd.png
#6.抽象工厂模式
代码:
package base.designpattern.creational;

/**
 * 抽象工厂模式
 * <p>
 * Created by yutianran on 16/7/1.
 */
public class AbstractFactoryPattern {

    public static void main(String[] args) {
        AbstractFactory factory = new ConcreteFactory1();
        AbstractProductA producta1 = factory.produceA();
        AbstractProductB productb1 = factory.produceB();
        producta1.methodA();
        productb1.methodB();
    }

    //抽象产品族
    public static abstract class AbstractProductA {
        public abstract void methodA();
    }

    public static abstract class AbstractProductB {
        public abstract void methodB();
    }

    //抽象工厂
    public static abstract class AbstractFactory {
        public abstract AbstractProductA produceA();

        public abstract AbstractProductB produceB();
    }

    //具体产品
    public static class ProductA1 extends AbstractProductA {
        @Override
        public void methodA() {
            System.out.println("Im ProductA1!");
        }
    }

    public static class ProductA2 extends AbstractProductA {
        @Override
        public void methodA() {
            System.out.println("Im ProductA2!");
        }
    }

    public static class ProductB1 extends AbstractProductB {
        @Override
        public void methodB() {
            System.out.println("Im ProductB1!");
        }
    }

    public static class ProductB2 extends AbstractProductB {
        @Override
        public void methodB() {
            System.out.println("Im ProductB2!");
        }
    }

    //具体工厂
    public static class ConcreteFactory1 extends AbstractFactory {
        @Override
        public AbstractProductA produceA() {
            return new ProductA1();
        }

        @Override
        public AbstractProductB produceB() {
            return new ProductB1();
        }
    }

    public static class ConcreteFactory2 extends AbstractFactory {
        @Override
        public AbstractProductA produceA() {
            return new ProductA2();
    
输出:
MyAttachment/05-Attachment/1458573-36917bcdb53b9e7b.png

© fishyer 2022