工厂模式--根据用户的实际需求生产具体的对象

工厂生产商品,什么工厂就生产什么商品

工厂和商品都是抽象的,“什么”才是具体的,也就是可实例化的

// 抽象商品类
public abstract class Product{
    var name: String

    public Product(name: String){
        this.name = name
    }

    //抽象方法
    public open func show(): Unit

}

// 商品A的继承
public class ProductA <: Product{
    public ProductA(name: String){
        super(name)
    }

    public override func show(): Unit{
        println(this.name)
    }
}

// 商品B的继承
public class ProductB <: Product{
    public ProductB(name: String){
        super(name)
    }

    public override func show(): Unit{
        println(this.name)
    }
}

// 抽象工厂类
public abstract class Factory{
    public func createProduct(): Product
}

// 生产商品A的工厂
public class FactortA<:Factory{
     public func createProduct(): Product{
        println("A工厂生产了")
        return ProductA("商品A")
     }
}

// 生产商品B的工厂
public class FactortB<:Factory{
     public func createProduct():Product{
        println("B工厂生产了")
        return ProductB("商品B")
     }
}

问:抽象方法用open而不直接写public func show(): Unit?

删掉确实可运行,抽象方法默认是可被重写的,就写这个public func show(): Unit,不需要open


题外话: 这个框子看起来简约,但复制的代码有空格,上面的则没有


实例化看看

    // 用户要生产商品B
    var user: Factory = FactortB()
    var product: Product = user.createProduct()
    product.show()
    // 又想生产商品A
    user = FactortA()
    product = user.createProduct()
    product.show()

结果如下: 

 


如果商品除种类外还有一层相关性(如质量等级、系列、使用对象、工厂条件等等),需要在工厂类中对商品进行约束,而不是直接什么工厂就生产什么商品。

// 抽象工厂模式
// AB两类,12两级
public abstract class Product3A{
    public func show(): Unit
}

public class Product3A_1 <: Product3A{
    public func show(){
        println("商品A_1")
    }
}

public class Product3A_2 <: Product3A{
    public func show(){
        println("商品A_2")
    }
}

public abstract class Product3B{
    public func show(): Unit
}

public class Product3B_1 <: Product3B{
    public func show(){
        println("商品B_1")
    }
}

public class Product3B_2 <: Product3B{
    public func show(){
        println("商品B_2")
    }
}

public abstract class Factory3{
    public func createProductA(): Product3A
    public func createProductB(): Product3B
}

public class Factory3_1 <: Factory3{
    public func createProductA(){
        println("1级工厂生产了")
        Product3A_1()
    }

    public func createProductB(){
        println("1级工厂生产了")
        Product3B_1()
    }
}

public class Factory3_2 <: Factory3{
    public func createProductA(){
        println("2级工厂生产了")
        Product3A_2()
    }

    public func createProductB(){
        println("2级工厂生产了")
        Product3B_2()
    }
}

这里约束1级工厂生产1级商品A_1、B_1,2级工厂生产2级商品A_2、B_2

    // 用user控制商品等级,用product控制商品种类
    var user: Factory3 = Factory3_1()
    var product: Product3A = user.createProductA()
    product.show()

 结果如下: 

 

Logo

讨论HarmonyOS开发技术,专注于API与组件、DevEco Studio、测试、元服务和应用上架分发等。

更多推荐