原型设计模式

原型设计模式介绍

原型设计模式(Prototype Pattern)是一种创建型设计模式,它通过复制现有对象(原型)来创建新对象,而无需通过构造函数重新初始化。这种模式特别适合以下场景:

  • • 当创建对象的成本较高(如需要复杂计算或资源加载)
  • • 当需要创建大量相似但略有不同的对象
  • • 当希望避免构造函数的限制或复杂性
  • • 当需要动态生成对象实例

原型模式的核心是实现克隆(clone)方法,通过复制已有对象来生成新对象,同时保持原始对象不受影响。

Java实现的原型模式示例

下面是一个Java实现的原型模式示例,模拟文档编辑器中的元素复制功能:

// 原型接口,定义克隆方法
public interface Prototype {
    Prototype clone();
    String display();
}
    
    // 图片元素原型
public class ImageElement implements Prototype {
    private String type = "image";
    private String src;
    private int width;
    private int height;
    
    public ImageElement(String src, int width, int height) {
        this.src = src;
        this.width = width;
        this.height = height;
    }
    
    // 图片元素特有的方法
    public void setDimensions(int width, int height) {
        this.width = width;
        this.height = height;
    }
    
    public void setSrc(String src) {
        this.src = src;
    }
    
    @Override
    public Prototype clone() {
        return new ImageElement(this.src, this.width, this.height);
    }
    
    @Override
    public String display() {
        return String.format("[Image: \"%s\", Dimensions: %dx%d]", 
                           src, width, height);
    }
}
    
    
    // 文本元素原型
public class TextElement implements Prototype {
    private String type = "text";
    private String content;
    private int fontSize;
    private String color;
    
    public TextElement(String content, int fontSize, String color) {
        this.content = content;
        this.fontSize = fontSize;
        this.color = color;
    }
    
    // 文本元素特有的方法
    public void setContent(String content) {
        this.content = content;
    }
    
    @Override
    public Prototype clone() {
        return new TextElement(this.content, this.fontSize, this.color);
    }
    
    @Override
    public String display() {
        return String.format("[Text: \"%s\", Size: %d, Color: %s]", 
                           content, fontSize, color);
    }
}
    
    
    // 演示原型模式的使用
public class PrototypeDemo {
    public static void main(String[] args) {
        // 创建原型对象
        TextElement headingPrototype = new TextElement("Heading", 24, "blue");
        TextElement paragraphPrototype = new TextElement("Paragraph text", 14, "black");
        ImageElement imagePrototype = new ImageElement("image.jpg", 300, 200);
        
        // 克隆原型并修改属性
        TextElement title = (TextElement) headingPrototype.clone();
        title.setContent("Welcome to My Page");
        
        TextElement intro = (TextElement) paragraphPrototype.clone();
        intro.setContent("This is a demo of the Prototype pattern");
        
        ImageElement profilePic = (ImageElement) imagePrototype.clone();
        profilePic.setDimensions(200, 200);
        profilePic.setSrc("profile.jpg");
        
        // 显示结果
        System.out.println("Original prototypes:");
        System.out.println(headingPrototype.display());
        System.out.println(paragraphPrototype.display());
        System.out.println(imagePrototype.display());
        
        System.out.println("\nCloned objects:");
        System.out.println(title.display());
        System.out.println(intro.display());
        System.out.println(profilePic.display());
    }
}
    

代码解析

Java实现原型模式通常有两种方式:

  1. 1. 通过接口实现(如示例所示):
    • • 定义Prototype接口,包含clone()方法
    • • 具体类实现该接口,在clone()方法中创建自身的副本
  2. 2. 通过继承Cloneable接口
    • • 利用Java提供的Cloneable标记接口和Object类的clone()方法
    • • 需要注意Cloneable机制默认实现的是浅拷贝

示例中的关键组件:

  • • Prototype接口:定义了克隆方法的标准
  • • 具体原型类TextElementImageElement实现了克隆方法
  • • 客户端代码:通过克隆原型对象创建新实例,并修改必要的属性

运行上述代码将输出:

Original prototypes:
[Text: "Heading", Size: 24, Color: blue]
[Text: "Paragraph text", Size: 14, Color: black]
[Image: "image.jpg", Dimensions: 300x200]

Cloned objects:
[Text: "Welcome to My Page", Size: 24, Color: blue]
[Text: "This is a demo of the Prototype pattern", Size: 14, Color: black]
[Image: "profile.jpg", Dimensions: 200x200]

这种实现方式的优势是类型安全且灵活,每个具体原型可以根据自身需求实现克隆逻辑,既可以是浅拷贝也可以是深拷贝。
更多参考资料

https://pan.baidu.com/s/1c1oQItiA7nZxz8Rnl3STpw?pwd=yftc
https://pan.quark.cn/s/dec9e4868381
Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐