• 设计模式——原型模式(Prototype Pattern)


      原型模式:用原型实例制定创建对象的种类,并且通过拷贝这些原型创建新的对象。

      UML 图:

      原型类:

    package com.cnblog.clarck;
    
    /**
     * 原型类
     * 
     * @author clarck
     * 
     */
    public abstract class Prototype {
        private String mID;
    
        public Prototype(String id) {
            mID = id;
        }
    
        public String getID() {
            return mID;
        }
    
        public abstract Prototype Clone();
    }

      具体原型类:

    package com.cnblog.clarck;
    
    /**
     * 要想真正拥有克隆的能力,就需要实现Cloneable接口,重写clone方法。通过克隆方法得到的对象得到的是一个本地的副本
     * 
     * @author clarck
     * 
     */
    public class ConcreatePrototype1 extends Prototype implements Cloneable {
    
        public ConcreatePrototype1(String id) {
            super(id);
        }
    
        @Override
        public Prototype Clone() {
            Prototype protoType = null;
            try {
                protoType = (Prototype) clone();
            } catch (CloneNotSupportedException e) {
                e.printStackTrace();
            }
    
            return protoType;
        }
        
    }
    package com.cnblog.clarck;
    
    /**
     * 要想真正拥有克隆的能力,就需要实现Cloneable接口,重写clone方法。通过克隆方法得到的对象得到的是一个本地的副本
     * 
     * @author clarck
     * 
     */
    public class ConcreatePrototype2 extends Prototype implements Cloneable {
    
        public ConcreatePrototype2(String id) {
            super(id);
        }
    
        @Override
        public Prototype Clone() {
            Prototype protoType = null;
            try {
                protoType = (Prototype) clone();
            } catch (CloneNotSupportedException e) {
                e.printStackTrace();
            }
    
            return protoType;
        }
    
    }

      测试类:

    package com.cnblog.clarck;
    
    /**
     * 测试类
     * 
     * @author clarck
     * 
     */
    public class Client {
        public static void main(String[] args) {
            ConcreatePrototype1 p1 = new ConcreatePrototype1("clarck");
            ConcreatePrototype1 c1 = (ConcreatePrototype1) p1.Clone();
            
            String str = String.format("id:%s", c1.getID());
            System.out.println(str);
            
            ConcreatePrototype1 p2 = new ConcreatePrototype1("clarck2");
            ConcreatePrototype1 c2 = (ConcreatePrototype1) p2.Clone();
            
            String str2 = String.format("id:%s", c2.getID());
            System.out.println(str2);
        }
    }
  • 相关阅读:
    Sudoku Solver [LeetCode]
    Populating Next Right Pointers in Each Node [LeetCode]
    Binary Tree Level Order Traversal [LeetCode]
    Clone Graph [LeetCode]
    Merge k Sorted Lists [LeetCode]
    Combinations [LeetCode]
    021 面向对象 一
    给图片加点料
    质数
    ex10 找出藏在字符串中的“密码”
  • 原文地址:https://www.cnblogs.com/tanlon/p/3391173.html
Copyright © 2020-2023  润新知