设计模式:(三)抽象工厂

包含角色:抽象工厂、具体工厂、一系列抽象产品、具体产品

问题:

用抽象工厂设计模式实现以下控制台应用程序theme 

主题工厂(Factory)能创建两个主题系列“白天”(Day)、“夜晚”

(Night),每个主题系列都包含了“颜色”(Color)、“字体”

(Font)两种组件。每个组件都有“创建(Create)方法,分别显示如下文字: 

白天的颜色

白天的字体

或者

夜晚的颜色

夜晚的字体

1. 一系列抽象产品

//抽象产品
public interface Theme
{
    void printTheme();
}

2. 具体产品 

//具体产品白天颜色
public class dayColor : Theme
{
    public void printTheme()
    {
        Console.WriteLine("白天的颜色");
    }
}
//具体产品夜晚颜色
public class nightColor : Theme
{
    public void printTheme()
    {
        Console.WriteLine("夜晚的颜色");
    }
}
//具体产品白天字体
public class dayFont : Theme
{
    public void printTheme()
    {
        Console.WriteLine("白天的字体");
    }
}
//具体产品夜晚字体
public class nightFont : Theme
{
    public void printTheme()
    {
        Console.WriteLine("夜晚的字体");
    }
}

3. 抽象工厂

//抽象工厂
public interface themeFactory
{
    Theme createColor();//创建颜色方法
    Theme createFont();//创建字体方法
}

4. 具体工厂

//具体工厂白天
public class Day : themeFactory
{
    public Theme createColor()
    {
        return new dayColor();
    }
    public Theme createFont()
    {
        return new dayFont();
    }
}
//具体工厂夜晚
public class Night : themeFactory
{
    public Theme createColor()
    {
        return new nightColor();
    }
    public Theme createFont()
    {
        return new nightFont();
    }
}

5. 测试

class Program
{
    static void Main(string[] args)
    {
        try
        {
            Theme themeColor;//定义对象,输出主题颜色
            Theme themeFont;//定义对象,输出主题字体
            string themeName = ConfigurationManager.AppSettings["ThemeName"];//反射+配置,参考设计模式(二)工厂模式
            themeFactory thFactory = (themeFactory)Assembly.Load("Project_name").CreateInstance("Project_name." + themeName);//Project_name项目名,根据自己创建的修改
            themeColor = thFactory.createColor();//调用create方法
            themeColor.printTheme();
            themeFont = thFactory.createFont();
            themeFont.printTheme();
            Console.ReadLine();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
            Console.ReadLine();
        }

    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值