通过set,get,willset,didset。
参照如下, 在之前工厂模式的基础上写了一份模型继承。
```
importUIKit
public enum FactoryType {
case Tech,Test,Production
}
class YZFactory {
var factoryName = ""
var myType = FactoryType.Production
static func createFactory(_ type: FactoryType) -> YZFactory {
letfactory:YZFactory
switchtype {
case.Tech:
factory =Technology()
case.Test:
factory =Testors()
default:
factory =Productions()
}
factory.myType= type
returnfactory
}
func createBreakfast() -> ProductType {
return YZProduct().createProduct()
}
var receivedModel:tmpModel?
var model: tmpModel? {
get{
print("我是父类get")
return receivedModel
}
set{
receivedModel = newValue
print("我是父类set")
}
}
}
class Technology: YZFactory {
override func createBreakfast() -> ProductType {
return DeveloperP().createProduct()
}
override var model: tmpModel? {
didSet{
ifmodel?.type==myType{
print("\(factoryName)\(model?.des??"")")
}else{
print("我不是被选中的,我是\(myType)")
}
}
}
}
class Testors: YZFactory {
override func createBreakfast() -> ProductType {
return TestorP().createProduct()
}
override var model: tmpModel? {
didSet{
ifmodel?.type==myType{
print("\(factoryName)\(model?.des??"")")
}else{
print("我不是被选中的,我是\(myType)")
}
}
}
}
class Productions: YZFactory {
override func createBreakfast() -> ProductType {
return ProductP().createProduct()
}
override var model: tmpModel? {
didSet{
ifmodel?.type==myType{
print("\(factoryName)\(model?.des??"")")
}else{
print("我不是被选中的,我是\(myType)")
}
}
}
}
struct tmpModel {
var type = FactoryType.Tech
var des = "88"
}
```
importUIKit
public enum ProductType {
case Develop,Test,Product
func getDescription() -> String {
switchself{
case.Develop:
return"开发"
case.Test:
return"测试"
default:
return"产品"
}
}
}
class YZProduct {
func createProduct() -> ProductType {
return ProductType.Develop
}
}
class DeveloperP: YZProduct {
override func createProduct() -> ProductType {
return ProductType.Develop
}
}
class TestorP: YZProduct {
override func createProduct() -> ProductType {
return ProductType.Test
}
}
class ProductP: YZProduct {
override func createProduct() -> ProductType {
return ProductType.Product
}
}
```
```
importUIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let tech = YZFactory.createFactory(.Tech)
let test = YZFactory.createFactory(.Test)
let production = YZFactory.createFactory(.Production)
let model = tmpModel(type: .Production, des: "888")
tech.model= model
print("-------1------")
test.model= model
print("-------2------")
production.model= model
print("-------3------")
}
}
```
网友评论