原型设计模式

2018-01-15  本文已影响0人  one_mighty

一、UML

Prototype.png

二、基本步骤

2.1、创建需要使用原型模式的类,实现Cloneable接口;
2.2、重写clone()方法,使用其父类的clone()方法构建一个对象;
2.3、将原对象的各个成员依次拷贝(赋值)给新创建的对象;
2.4、将新对象返回,需要做异常处理;

三、实现方式

3.1、定义
/**
 * @author lizihanglove
 * @date 2018/1/12
 * @email one_mighty@163.com
 * @desc 原型设计模式
 */

public class UrlPrototype implements Cloneable {
    private String host;
    private String port;
    private String protocol;

    public void printUrl() {
        System.out.println("The Url is:"+protocol+"//"+host+":"+port);
    }

    @Override
    public UrlPrototype clone() {
        try {
            UrlPrototype urlPrototype = (UrlPrototype) super.clone();
            urlPrototype.host = this.host;
            urlPrototype.port = this.port;
            urlPrototype.protocol = this.protocol;
            return urlPrototype;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public String getHost() {
        return host;
    }

    public void setHost(String host) {
        this.host = host;
    }

    public String getPort() {
        return port;
    }

    public void setPort(String port) {
        this.port = port;
    }

    public String getProtocol() {
        return protocol;
    }

    public void setProtocol(String protocol) {
        this.protocol = protocol;
    }
}

3.2、调用
  UrlPrototype original = new UrlPrototype();
        original.setHost("www.lizihanglove.website");
        original.setPort("8080");
        original.setProtocol("https");
        original.printUrl();
        System.out.println("--------------------------------------");
        UrlPrototype reborn = original.clone();
        reborn.printUrl();
        System.out.println("--------------------------------------");
        reborn.setPort("80");
        reborn.setProtocol("http");
        reborn.printUrl();


3.3、结果
System.out: The Url is:https//www.lizihanglove.website:8080
System.out: --------------------------------------
System.out: The Url is:https//www.lizihanglove.website:8080
System.out: --------------------------------------
System.out: The Url is:http//www.lizihanglove.website:80
上一篇 下一篇

猜你喜欢

热点阅读