Core Design Patterns(11) Abstract Factory 抽象工厂模式
VS 2008
针对多个平行产品体系的产品创建问题,使用抽象工厂模式
1. 模式UML图

2. 应用
考虑应用程序支持多种数据库的设计,对于领域对象的数据库访问层定义数据访问的接口,分别提供基于SqlServer的实现和基于Oracle的实现。

IUser.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DesignPattern.AbstractFactory.DAL {
public interface IUser {

void Operation();
}
}
SqlUser.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DesignPattern.AbstractFactory.DAL {
public class SqlUser : IUser {
IUser Members
}
}
OracleUser.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DesignPattern.AbstractFactory.DAL {
public class OracleUser : IUser {
IUser Members
}
}
ITopic.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DesignPattern.AbstractFactory.DAL {
public interface ITopic {

void Operation();
}
}
SqlTopic.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DesignPattern.AbstractFactory.DAL {
public class SqlTopic : ITopic {
ITopic Members
}
}
OracleTopic.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DesignPattern.AbstractFactory.DAL {
public class OracleTopic: ITopic {
ITopic Members
}
}
IDALFactory.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DesignPattern.AbstractFactory.DAL {
public interface IDALFactory {

IUser CreateUser();
ITopic CreateTopic();
}
}
SqlFactory.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DesignPattern.AbstractFactory.DAL {
public class SqlFactory : IDALFactory {
IDALFactory Members
}
}
OracleFactory.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DesignPattern.AbstractFactory.DAL {
public class OracleFactory : IDALFactory {
IDALFactory Members
}
}
Client
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DesignPattern.AbstractFactory.DAL;

namespace DesignPattern.AbstractFactory {
class Program {
static void Main(string[] args) {

IDALFactory sqlFactory = new SqlFactory();
IUser sqlUser = sqlFactory.CreateUser();
sqlUser.Operation();

ITopic sqlTopic = sqlFactory.CreateTopic();
sqlTopic.Operation();

IDALFactory oracleFactory = new OracleFactory();
IUser oracleUser = oracleFactory.CreateUser();
oracleUser.Operation();

ITopic oracleTopic = oracleFactory.CreateTopic();
oracleTopic.Operation();
}
}
}
Output
针对多个平行产品体系的产品创建问题,使用抽象工厂模式
1. 模式UML图

2. 应用
考虑应用程序支持多种数据库的设计,对于领域对象的数据库访问层定义数据访问的接口,分别提供基于SqlServer的实现和基于Oracle的实现。

IUser.cs












SqlUser.cs











OracleUser.cs











ITopic.cs












SqlTopic.cs











OracleTopic.cs











IDALFactory.cs













SqlFactory.cs











OracleFactory.cs











Client



























Output
