跟我一起学“仓颉”设计模式-原型模式练习题

发布时间:2026/6/9 5:12:15

跟我一起学“仓颉”设计模式-原型模式练习题 一、练习题1. 为销售管理系统里的客户类Customer实现克隆方法该类里面包含了客户姓名和客户的地址Address分别用浅克隆和深克隆实现并解释浅克隆和深克隆的区别。类图核心代码package DesignPattern.prototype // 抽象原型 public abstract class Property { public func clone(): Property } public class Address { public var name: String public init (name: String) { this.name name } } // 具体原型 public class Customer : Property { public Customer(public var name: String, public var address: Address){} public func getInfo() { println(姓名: ${name}, 地址: ${address.name}) } public override func clone() { return Customer(name, address) } }测试代码package DesignPattern import DesignPattern.prototype.* main(): Int64 { let customer1 Customer(小余, Address(翻斗花园)) customer1.getInfo() // 浅克隆 println(\n浅克隆) let customer2 customer1 customer2.name 小李 customer2.address Address(水帘洞) customer1.getInfo() customer2.getInfo() // 深克隆 println(\n深克隆) let customer3 customer1.clone() customer3.name 小刘 customer3.address Address(汤臣一品) customer1.getInfo() customer2.getInfo() customer3.getInfo() return 0 }区别浅克隆只会复制值类型数据引用类型不会复制深克隆无论是值类型还是引用类型都会复制一份给克隆对象。二、小结本章为大家详细的介绍了仓颉设计模式中原型模式练习题的内容下一章为大家带来适配器模式的内容。最后创作不易如果大家觉得我的文章对学习仓颉设计模式有帮助的话就动动小手点个免费的赞吧收到的赞越多我的创作动力也会越大哦谢谢大家

相关新闻