设计模式-抽象工厂

抽象工厂模式是一种创建型设计模式,它提供了一种方式来封装一组具有共同主题的单独工厂。抽象工厂模式通过提供一个超级工厂创建其他工厂的接口,使得客户端使用抽象的接口操作具体对象,从而实现客户端与具体工厂类解耦。

using System;  

// 抽象产品A  
public abstract class AbstractProductA  
{  
    public abstract string Use();  
}  

// 抽象产品B  
public abstract class AbstractProductB  
{  
    public abstract string Eat();  
}  

// 具体产品A1  
public class ProductA1 : AbstractProductA  
{  
    public override string Use()  
    {  
        return "Using Product A1";  
    }  
}  

// 具体产品A2  
public class ProductA2 : AbstractProductA  
{  
    public override string Use()  
    {  
        return "Using Product A2";  
    }  
}  

// 具体产品B1  
public class ProductB1 : AbstractProductB  
{  
    public override string Eat()  
    {  
        return "Eating Product B1";  
    }  
}  

// 具体产品B2  
public class ProductB2 : AbstractProductB  
{  
    public override string Eat()  
    {  
        return "Eating Product B2";  
    }  
}  

// 抽象工厂  
public abstract class AbstractFactory  
{  
    public abstract AbstractProductA CreateProductA();  
    public abstract AbstractProductB CreateProductB();  
}  

// 具体工厂1  
public class Factory1 : AbstractFactory  
{  
    public override AbstractProductA CreateProductA()  
    {  
        return new ProductA1();  
    }  

    public override AbstractProductB CreateProductB()  
    {  
        return new ProductB1();  
    }  
}  

// 具体工厂2  
public class Factory2 : AbstractFactory  
{  
    public override AbstractProductA CreateProductA()  
    {  
        return new ProductA2();  
    }  

    public override AbstractProductB CreateProductB()  
    {  
        return new ProductB2();  
    }  
}  

// 客户端代码  
public class Client  
{  
    public static void ClientCode(AbstractFactory factory)  
    {  
        AbstractProductA productA = factory.CreateProductA();  
        AbstractProductB productB = factory.CreateProductB();  

        Console.WriteLine(productA.Use());  
        Console.WriteLine(productB.Eat());  
    }  

    public static void Main(string[] args)  
    {  
        AbstractFactory factory1 = new Factory1();  
        AbstractFactory factory2 = new Factory2();  

        Console.WriteLine("Using the products created by Factory 1:");  
        ClientCode(factory1);  

        Console.WriteLine("Using the products created by Factory 2:");  
        ClientCode(factory2);  
    }  
}
posted @ 2024-10-28 10:15  .Neterr  阅读(4)  评论(0编辑  收藏  举报