设计模式 原型模式练习

设计模式原型模式练习

题目链接

原型模式-矩形原型

什么是原型模式

原型模式一种创建型设计模式,该模式的核心思想是基于现有的对象创建新的对象,而不是从头开始创建。

在原型模式中,通常有一个原型对象,它被用作创建新对象的模板。新对象通过复制原型对象的属性和状态来创建,而无需知道具体的创建细节。

为什么要使用原型模式

如果一个对象的创建过程比较复杂时(比如需要经过一系列的计算和资源消耗),那每次创建该对象都需要消耗资源,而通过原型模式就可以复制现有的一个对象来迅速创建/克隆一个新对象,不必关心具体的创建细节,可以降低对象创建的成本。

原型模式的基本实现

原型模式的实现过程即上面描述模块的实现过程:

创建一个抽象类或接口,声明一个克隆方法clone
实现具体原型类,重写克隆方法
客户端中实例化具体原型类的对象,并调用其克隆方法来创建新的对象。

本题代码

import java.util.Scanner;
 
// 抽象原型类
abstract class Prototype implements Cloneable {
    public abstract Prototype clone();
    public abstract String getDetails();
 
    // 公共的 clone 方法
    public Prototype clonePrototype() {
        try {
            return (Prototype) super.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
            return null;
        }
    }
}
 
// 具体矩形原型类
class RectanglePrototype extends Prototype {
    private String color;
    private int width;
    private int height;
 
    // 构造方法
    public RectanglePrototype(String color, int width, int height) {
        this.color = color;
        this.width = width;
        this.height = height;
    }
 
    // 克隆方法
    @Override
    public Prototype clone() {
        return clonePrototype();
    }
 
    // 获取矩形的详细信息
    @Override
    public String getDetails() {
        return "Color: " + color + ", Width: " + width + ", Height: " + height;
    }
}
 
// 客户端程序
public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
 
        // 读取需要创建的矩形数量
        int N = scanner.nextInt();
 
        // 读取每个矩形的属性信息并创建矩形对象
        for (int i = 0; i < N; i++) {
            String color = scanner.next();
            int width = scanner.nextInt();
            int height = scanner.nextInt();
 
            // 创建原型对象
            Prototype originalRectangle = new RectanglePrototype(color, width, height);
 
            // 克隆对象并输出详细信息
            Prototype clonedRectangle = originalRectangle.clone();
            System.out.println(clonedRectangle.getDetails());
        }
    }
}
  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值