原型模式
用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。用于一个对象的构建代价过高时。
案例: 考虑一个图形编辑软件的场景,其中需要频繁地创建、编辑和复制各种图形对象,如圆形、矩形等。每种图形对象都有一些共同的属性,比如位置、颜色和大小,但是每种图形的绘制方法可能不同。定义一个基础的图形接口Shape作为原型,然后为每种具体的图形实现这个接口。
interface Shape {
x: number;
y: number;
color: string;
clone(): Shape;
}
class Rectangle implements Shape {
x: number;
y: number;
color: string;
width: number;
height: number;
constructor(source?: Rectangle) {
this.x = source ? source.x : 0;
this.y = source ? source.y : 0;
this.color = source ? source.color : 'white';
this.width = source ? source.width : 0;
this.height = source ? source.height : 0;
}
clone(): Rectangle {
return new Rectangle(this);
}
}
class Circle implements Shape {
x: number;
y: number;
color: string;
radius: number;
constructor(source?: Circle) {
this.x = source ? source.x : 0;
this.y = source ? source.y : 0;
this.color = source ? source.color : 'white';
this.radius = source ? source.radius : 0;
}
clone(): Circle {
return new Circle(this);
}
}
// 创建一个原始矩形
const originalRectangle = new Rectangle();
originalRectangle.width = 10;
originalRectangle.height = 20;
originalRectangle.color = 'blue';
// 使用原型模式克隆矩形
const clonedRectangle = originalRectangle.clone();
console.log(clonedRectangle);
// 创建一个原始圆形
const originalCircle = new Circle();
originalCircle.radius = 5;
originalCircle.color = 'red';
// 使用原型模式克隆圆形
const clonedCircle = originalCircle.clone();
console.log(clonedCircle);
Rectangle和Circle类通过实现clone方法,允许从现有对象创建一个完全独立的复制品。使用原型模式使得复制图形对象变得简单和高效。