美文网首页
Swift---抽象工厂模式

Swift---抽象工厂模式

作者: BabyNeedCare | 来源:发表于2021-12-10 10:12 被阅读0次

抽象工厂模式:

YZFactory.swift

import UIKit

public enum FactoryType {
    
    case Tech,Test,Production
}

class YZFactory {
    
    var factoryName = ""
    
    var myType = FactoryType.Production
    
   static func createFactory(_ type: FactoryType) -> YZFactory {
        
        let factory: YZFactory
       
        switch type {
        case .Tech:
            factory = Technology()
        case .Test:
            factory = Testors()
        default:
            factory = Productions()
        }
       factory.myType = type
        return factory
    }
    
    func createBreakfast() -> ProductType {
        
        return YZProduct().createProduct()
    }
}


class Technology: YZFactory {
    
    override func createBreakfast() -> ProductType {
        
        return DeveloperP().createProduct()
    }
}

class Testors: YZFactory {
    
    override func createBreakfast() -> ProductType {
        return TestorP().createProduct()
    }
}

class Productions: YZFactory {
    
    override func createBreakfast() -> ProductType {
        return ProductP().createProduct()
    }
}

YZProduct.swift

import UIKit

public enum ProductType {
    
    case Develop,Test,Product
    
    func getDescription() -> String {
        
        switch self {
        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
    }
}

调用:

        print(YZFactory.createFactory(.Tech).createBreakfast().getDescription())
        print(YZFactory.createFactory(.Test).createBreakfast().getDescription())
        print(YZFactory.createFactory(.Production).createBreakfast().getDescription())

开发
测试
产品

相关文章

网友评论

      本文标题:Swift---抽象工厂模式

      本文链接:https://www.haomeiwen.com/subject/tshcfrtx.html