[原创]简单工厂模式和抽象工厂模式

本文介绍了简单工厂模式和抽象工厂模式的区别与应用。通过具体示例展示了如何使用简单工厂模式来创建不同业务接口对象,并解释了其局限性。进一步探讨了抽象工厂模式的优势,即通过一次配置即可获取不同实例的工厂。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

简单工厂模式

假设不同实现的DAL层,抽象出一个IDAL接口层,工厂模式的作用就是根据配置,获得不同实现的DAL层

 /// <summary>
    /// 简单工厂,提供众多 简单工厂方法,来创建 不同的 业务接口对象
    /// </summary>
    public class BLLAbsFatoryFake
    {
        public IBLL.IUsers GetBLLUser()
        {
            string strType = System.Configuration.ConfigurationManager.AppSettings["bllType"].ToString();

            if (strType == "bll")
            {
                return new BLL.Users();
            }
            else
            {
                return new BLLA.Users();
            }
        }

        public IBLL.IMsg GetBLLMsg()
        {
            string strType = System.Configuration.ConfigurationManager.AppSettings["bllType"].ToString();

            if (strType == "bll")
            {
                return new BLL.Msg();
            }
            else
            {
                return new BLLA.Msg();
            }
        }
    }

但是简单工厂的问题是每获取一个DAL类都需要根据配置选择一次。

抽象工厂则只是判断获取不同实例的工厂。

    /// <summary>
    /// 业务抽象工厂类
    /// </summary>
    public abstract class AbsFactoryBLL
    {
        /// <summary>
        /// 根据配置文件 获取 实体业务工厂 对象
        /// </summary>
        /// <returns></returns>
        public static AbsFactoryBLL GetFatory()
        {
            string strType = System.Configuration.ConfigurationManager.AppSettings["bllType"].ToString();
            AbsFactoryBLL bllFactory = null;
            switch (strType)
            { 
                case "bll":
                    bllFactory = new BLLFactory();
                    break;
                case "blla":
                    bllFactory = new BLLFactoryA();
                    break;
            }
            return bllFactory;
        }

        public abstract IBLL.IUsers GetUser();
        public abstract IBLL.IMsg GetMsg();
    }

 

转载于:https://www.cnblogs.com/520yang/articles/4535222.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值