Java设计模式:原型

当经常创建非常相似的对象时,使用原型设计模式。原型模式将克隆对象并设置更改的功能。这样,消耗的资源更少。

1.原型模式类图

在这里插入图片描述
2.原型模式Java示例

package designpatterns.prototype;
 
//prototype
interface Prototype {
    void setSize(int x);
    void printSize();
 }
 
//一个具体的类
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();
    }
}
 
///当我们需要大量类似的对象时,
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();
        }
    }
}
  1. Java标准库中使用的原型设计模式

java.lang.Object-clone()

在这里插入图片描述

发布了0 篇原创文章 · 获赞 0 · 访问量 93

猜你喜欢

转载自blog.csdn.net/qq_41806546/article/details/105136566