创建型---原型模式

举报
斌哥来了 发表于 2021/07/29 10:25:18 2021/07/29
6.5k+ 0 0
【摘要】 // 基础原型。 abstract class Shape is field X: int field Y: int field color: string // 常规构造函数。 constructor Shape() is // ... // 原型构造函数。使用已有对象的数值来初始化一个新对象。 constructor Shape(source: Shap...







// 基础原型。

abstract class Shape is

field X: int

field Y: int

field color: string

// 常规构造函数。

constructor Shape() is

// ...

// 原型构造函数。使用已有对象的数值来初始化一个新对象。

constructor Shape(source: Shape) is

this()

this.X = source.X

this.Y = source.Y

this.color = source.color

// clone (克隆)操作会返回一个形状子类。

abstract method clone():Shape

// 具体原型。克隆方法会创建一个新对象并将其传递给构造函数。直到构造函数运

// 行完成前,它都拥有指向新克隆对象的引用。因此,任何人都无法访问未完全生

// 成的克隆对象。这可以保持克隆结果的一致。

class Rectangle extends Shape is

field width: int

field height: int

constructor Rectangle(source: Rectangle) is

// 需要调用父构造函数来复制父类中定义的私有成员变量。

super(source)

this.width = source.width

this.height = source.height

method clone():Shape is

return new Rectangle(this)

class Circle extends Shape is

field radius: int

constructor Circle(source: Circle) is

super(source)

this.radius = source.radius

method clone():Shape is

return new Circle(this)

// 客户端代码中的某个位置。

class Application is

field shapes: array of Shape

constructor Application() is

Circle circle = new Circle()

circle.X = 10

circle.Y = 10

circle.radius = 20

shapes.add(circle)

Circle anotherCircle = circle.clone()

shapes.add(anotherCircle)

// 变量 `anotherCircle (另一个圆) ` `circle (圆) ` 对象的内

// 容完全一样。

Rectangle rectangle = new Rectangle()

rectangle.width = 10

rectangle.height = 20

shapes.add(rectangle)

method businessLogic() is

// 原型是很强大的东西,因为它能在不知晓对象类型的情况下生成一个与

// 其完全相同的复制品。

Array shapesCopy = new Array of Shapes.

// 例如,我们不知晓形状数组中元素的具体类型,只知道它们都是形状。

// 但在多态机制的帮助下,当我们在某个形状上调用 `clone (克隆) `

// 方法时,程序会检查其所属的类并调用其中所定义的克隆方法。这样,

// 我们将获得一个正确的复制品,而不是一组简单的形状对象。

foreach (s in shapes) do

shapesCopy.add(s.clone())

// `shapesCopy (形状副本) ` 数组中包含 `shape (形状) ` 数组所有

// 子元素的复制品。




【版权声明】本文为华为云社区用户原创内容,未经允许不得转载,如需转载请自行联系原作者进行授权。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

作者其他文章

评论(0

抱歉,系统识别当前为高风险访问,暂不支持该操作

    全部回复

    上滑加载中

    设置昵称

    在此一键设置昵称,即可参与社区互动!

    *长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

    *长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。