zoukankan      html  css  js  c++  java
  • 十六.抽象工厂模式

    抽象工厂模式:

           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();

           }

        }

  • 相关阅读:
    前端页面的防抖与节流
    vue3.0 响应式原理
    cssBEM命名规范及常用CSS class 命名
    vue2.x 响应式原理
    npm 相关命令
    Node之 fs
    Node 之 Buffer
    Node之path
    Node之process
    Node.js 如何处理 ES6 模块
  • 原文地址:https://www.cnblogs.com/yaoge/p/1815238.html
Copyright © 2011-2022 走看看