forked from AmazingCode/DesignModel
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path8、工厂方法模式.cs
65 lines (63 loc) · 1.4 KB
/
8、工厂方法模式.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
/// <summary>
/// 工厂模式存在类与switch语句的高耦合,增加新的类 需要去增加case分支,违背了开放-封闭原则
/// 工厂方法模式可以解决这个问题。
/// </summary>
class 工厂方法模式
{
public void Main()
{
SubFactory sf=new SubFactory();
Operator op=sf.CreateOperator();
op.NumberA = 10;
op.NumberB = 5;
op.GetResult();
}
}
public abstract class Operator
{
public double NumberA;
public double NumberB;
public virtual double GetResult()
{
return 0;
}
}
public class Add1:Operator
{
public override double GetResult()
{
return NumberA+NumberB;
}
}
public class Sub1:Operator
{
public override double GetResult()
{
return NumberA-NumberB;
}
}
interface IFactory
{
Operator CreateOperator();
}
class AddFactory:IFactory
{
public Operator CreateOperator()
{
return new Add1();
}
}
class SubFactory:IFactory
{
public Operator CreateOperator()
{
return new Sub1();
}
}
}