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

2019-12-26 11:27:48刘景俊
易采站长站为您分析浅谈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();
        }
    }
}