跟我一起学“仓颉”设计模式-原型模式练习题
一、练习题
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 }区别:浅克隆只会复制值类型数据,引用类型不会复制,深克隆无论是值类型还是引用类型,都会复制一份给克隆对象。
二、小结
本章为大家详细的介绍了仓颉设计模式中原型模式练习题的内容,下一章,为大家带来适配器模式的内容。最后,创作不易,如果大家觉得我的文章对学习仓颉设计模式有帮助的话,就动动小手,点个免费的赞吧!收到的赞越多,我的创作动力也会越大哦,谢谢大家🌹🌹🌹!!!
