zoukankan      html  css  js  c++  java
  • [译]Java 设计模式之原型

    (文章翻译自Java Design Pattern: Prototype

    原型模式用于当当非常相似的对象频繁被需要的时候。原型模式克隆了对象并且设置变化的特征。这种方式会消耗更少的资源。考虑下为什么会消耗更少的资源?

    1.原型模式类图

    prototype-pattern-class-diagram

    2.原型模式Java例子

    package designpatterns.prototype;
     
    //prototype
    interface Prototype {
        void setSize(int x);
        void printSize();
     }
     
    // a concrete class
    class A implements Prototype, Cloneable {
        private int size;
     
        public A(int x) {
            this.size = x;
        }
     
        @Override
        public void setSize(int x) {
            this.size = x;
        }
     
        @Override
        public void printSize() {
            System.out.println("Size: " + size);
        }
     
     
        @Override
        public A clone() throws CloneNotSupportedException {
            return (A) super.clone();
        }
    }
     
    //when we need a large number of similar objects
    public class PrototypeTest {
        public static void main(String args[]) throws CloneNotSupportedException {
            A a = new A(1);
     
            for (int i = 2; i < 10; i++) {
                Prototype temp = a.clone();
                temp.setSize(i);
                temp.printSize();
            }
        }
    }
    

    3.原型设计模式在Java表中类库中的使用

    java.lang.Object - clone()

  • 相关阅读:
    thinkphp 事物回滚
    文字超出部分以省略号隐藏
    js倒计时
    js 日期转为时间戳
    jquery 获取url地址参数
    spreadjs 自定义菜单事件
    spreadjs 点击事件
    spreadjs 自定义上传文件单元格
    spreadjs 小记
    Json数组排序
  • 原文地址:https://www.cnblogs.com/zhangminghui/p/4214386.html
Copyright © 2011-2022 走看看