栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C# > C#教程

浅谈C#设计模式之工厂模式

C#教程 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

浅谈C#设计模式之工厂模式

工厂模式和简单工厂有什么区别。废话不多说,对比第一篇例子应该很清楚能看出来。

优点: 工厂模式弥补了简单工厂模式中违背开放-封闭原则,又保持了封装对象创建过程的优点。

复制代码 代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DesignModel
{
    public interface Factory
    {
        JS createjs();
    }
    public class JS
    {
        public int NumA { get; set; }
        public int NumB { get; set; }
        public virtual int GetResult()
        {
            return 0;
        }
    }
    public class Add1 : JS
    {
        public override int GetResult()
        {
            return NumA + NumB;
        }
    }
    public class Sub1 : JS
    {
        public override int GetResult()
        {
            return NumA - NumB;
        }
    }
    public class AddFactory : Factory
    {
        public JS createjs()
        {
            return new Add1();
        }
    }
    public class SubFactory: Factory
    {
        public JS createjs()
        {
            return new Sub1();
        }
    }
}

客户端调用:

复制代码 代码如下:
  Factory factory = new AddFactory();
            JS  js = factory.createjs();
            js.NumA = 1;
            js.NumB = 2;
            Console.WriteLine( js.GetResult());
            Factory f = new SubFactory();
            JS J= f.createjs();
            J.NumA = 9;
            J.NumB = 0;
            Console.WriteLine(J.GetResult());
            Console.ReadLine();

这里主要是对比了下和简单工厂模式的区别,记录下来,以防自己搞混。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/125795.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号