十六.抽象工厂模式

抽象工厂模式:

       AbstractFactory提供一个创建一系列相关或相互依赖对象的接口,而无需指定它们具体的类。

 

Demo

       interface  IFactory//抽象工厂接口,包含所有产品创建的抽象方法

    {

       IUser CreateUser();

       IAdmin CreateAdmin();

    }

   class SqlServerFactory : IFactory//具体工厂

    {

       public IUser CreateUser()

       {

           return new SqlServerUser();

       }

       public IAdmin CreateAdmin()

       {

           return new SqlServerAdmin();

       }

    }

   class AccessFactory : IFactory

    {

       public IUser CreateUser()

       {

            return new AccessUser();

       }

       public IAdmin CreateAdmin()

       {

           return new AccessAdmin();

       }

}

 

       //用于客户端访问,解除与具体数据库访问的耦合

   interface IAdmin//抽象产品

    {

       void Insert(Admin admin);

       Admin GetAdmin(int id);

    }

   class SqlServerAdmin : IAdmin//产品的具体实现

    {

       public void Insert(Admin admin)

       {

           Console.WriteLine("在sql数据库中插入admin");

       }

       public Admin GetAdmin(int id)

       {

           Console.WriteLine("在Sql中根据ID查询admin");

           return null;

       }

    }

   class AccessAdmin : IAdmin

    {

       public void Insert(Admin admin)

       {

           Console.WriteLine("在Access中插入admin");

       }

       public Admin GetAdmin(int id)

       {

           Console.WriteLine("在Access中根据ID查询Admin");

           return null;

       }

    }

 

       class Program

    {

       //抽象工厂,结构与ConsoleApp2相同。因为有多个对象(User,admin)所以将对象抽象

       static void Main(string[] args)

       {

           User user = new User();

           Admin admin = new Admin();

 

           IFactory factory = new AccessFactory();//选择数据库类型

 

           IUser iu = factory.CreateUser();

           iu.Insert(user);

           iu.GetUser(1);

 

           IAdmin ia = factory.CreateAdmin();

           ia.Insert(admin );

           ia.GetAdmin(1);

 

           Console.ReadKey();

       }

    }

你可能感兴趣的:(抽象工厂模式)