码迷,mamicode.com
首页 > 其他好文 > 详细

31、面向对象设计模式之工厂方法模式概念的提升

时间:2020-06-16 18:43:46      阅读:54      评论:0      收藏:0      [点我收藏+]

标签:工厂   概念   面向对象设计   span   ret   ati   pen   tor   method   

例子如下:

public abstract class Product{
    public string productName;
}
public abstract class ProductFactory{
    public Product FactoryMethod(string producTypeName){
        Product product;
        product = CreateProduct(producTypeName);
        return product;
    }
    
    public abstract CreateProduct(string productName);
}

public class ProductA : Product{
    public ProductA(){
        
        productName = "ProductA";
    }
}

public class ProductB : Product{
    public ProductB(){
        
        productName = "ProductB";
    }
}
public class ProductC : Product{
    public ProductC(){
        
        productName = "ProductC";
    }
}
public class ProductD : Product{
    public ProductD(){
        
        productName = "ProductD";
    }
}
public class ProductFactoryA : ProductFactory{
    
    public override Product CreateProduct(string producName){
        switch(producName){
            case "A":
                return new ProductA();
            case "B":
                return new ProductB();
        }
        return null;
    }
}
public class ProductFactoryB :ProductFactory{
    public override Product CreateProduct(string producName){
        switch(producName){
            case "C":
                return new ProductC();
            case "D":
                return new ProductD();
        }
        return null;
    }
}
class Program{
    
    static void Main(string[] args){
        ProductFactory myProductFactory = new ProductFactoryA();
        Product myProduct = myProductFactory.FactoryMethod("A");
        Console.WriteLine(myProduct.productName);
        myProduct = myProduct.FactoryMethod("B");
        Console.WriteLine(myProduct.producName);
        ProductFactory myProductFactoryB = new ProductFactoryB();
        Product myProductB = myProductFactoryB.FactoryMethod("C")
        Console.WriteLine(myProductB.producName);
        myProductB = myProductFactoryB.FactoryMethod("D");
        Console.WriteLine(myProduct.producName);
    }
}

 

31、面向对象设计模式之工厂方法模式概念的提升

标签:工厂   概念   面向对象设计   span   ret   ati   pen   tor   method   

原文地址:https://www.cnblogs.com/sy-liu/p/13143377.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!