包含角色:抽象工厂、具体工厂、一系列抽象产品、具体产品
问题:
用抽象工厂设计模式实现以下控制台应用程序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();
}
}
}