예제 코드

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
66
67
68
69
70
71
72
73
74
75
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace CSharp_StrategyPattern
{
    abstract class Strategy
    {
        public abstract void AlgorithmInterface();
    }
 
    class ConcreteStrategyA : Strategy
    {
        public override void AlgorithmInterface()
        {
            Console.WriteLine(
              "Called ConcreteStrategyA.AlgorithmInterface()");
        }
    }
 
    class ConcreteStrategyB : Strategy
    {
        public override void AlgorithmInterface()
        {
            Console.WriteLine(
              "Called ConcreteStrategyB.AlgorithmInterface()");
        }
    }
 
    class ConcreteStrategyC : Strategy
    {
        public override void AlgorithmInterface()
        {
            Console.WriteLine(
              "Called ConcreteStrategyC.AlgorithmInterface()");
        }
    }
 
    class Context
    {
        private Strategy _strategy;
        
        public Context(Strategy strategy)
        {
            this._strategy = strategy;
        }
 
        public void ContextInterface()
        {
            _strategy.AlgorithmInterface();
        }
    }
 
    class Program
    {
        static void Main(string[] args)
        {
            Context context;
 
            context = new Context(new ConcreteStrategyA());
            context.ContextInterface();
 
            context = new Context(new ConcreteStrategyB());
            context.ContextInterface();
 
            context = new Context(new ConcreteStrategyC());
            context.ContextInterface();
 
            Console.ReadKey();
        }
    }
}
 
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace CSharp_ObserverPattern
{   
    abstract class Observer
    {
        public abstract void Update();
    }
    
    class ConcreteObserver : Observer
    {
        private string _name;
        private string _observerState;
        private ConcreteSubject _subject;
        
        public ConcreteObserver(ConcreteSubject subject, string name)
        {
            this._subject = subject;
            this._name = name;
        }
        
        public override void Update()
        {
            _observerState = _subject.SubjectState;
            Console.WriteLine("Observer {0}'s new state is {1}", _name, _observerState);
        }
 
        public ConcreteSubject Subject { get; set; }        
    }
 
    abstract class Subject
    {
        private List<Observer> _observers = new List<Observer>();
 
        public void Attach(Observer observer)
        {
            _observers.Add(observer);
        }
 
        public void Detach(Observer observer)
        {
            _observers.Remove(observer);
        }
 
        public void Notify()
        {
            foreach (Observer o in _observers)
            {
                o.Update();
            }
        }
    }
 
    class ConcreteSubject : Subject
    {
        public string SubjectState { get; set; }
    }
 
    class Program
    {
        static void Main(string[] args)
        {
            ConcreteSubject s = new ConcreteSubject();
 
            s.Attach(new ConcreteObserver(s, "X"));
            s.Attach(new ConcreteObserver(s, "Y"));
            s.Attach(new ConcreteObserver(s, "Z"));
             
            s.SubjectState = "ABC";
            s.Notify();
  
            Console.ReadKey();
        }
    }
}
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace CSharp_MediatorPattern
{
    abstract class Mediator
    {
        public abstract void Send(string message, Colleague colleague);
    }
 
    class ConcreteMediator : Mediator
    {
        private ConcreteColleague1 _colleague1;
        private ConcreteColleague2 _colleague2;
 
        public ConcreteColleague1 Colleague1
        {
            set { _colleague1 = value; }
        }
 
        public ConcreteColleague2 Colleague2
        {
            set { _colleague2 = value; }
        }
 
        public override void Send(string message, Colleague colleague)
        {
            if (colleague == _colleague1)
            {
                _colleague2.Notify(message);
            }
            else
            {
                _colleague1.Notify(message);
            }
        }
    }
 
    abstract class Colleague
    {
        protected Mediator mediator;
 
        public Colleague(Mediator mediator)
        {
            this.mediator = mediator;
        }
    }
 
    class ConcreteColleague1 : Colleague
    {
        public ConcreteColleague1(Mediator mediator) : base(mediator)
        {
        }
 
        public void Send(string message)
        {
            mediator.Send(message, this);
        }
 
        public void Notify(string message)
        {
            Console.WriteLine("Colleague1 gets message: " + message);
        }
    }
    
    class ConcreteColleague2 : Colleague
    {
        public ConcreteColleague2(Mediator mediator) : base(mediator)
        {
        }
 
        public void Send(string message)
        {
            mediator.Send(message, this);
        }
 
        public void Notify(string message)
        {
            Console.WriteLine("Colleague2 gets message: " + message);
        }
    }
 
    class Program
    {
        static void Main(string[] args)
        {
            ConcreteMediator m = new ConcreteMediator();
 
            ConcreteColleague1 c1 = new ConcreteColleague1(m);
            ConcreteColleague2 c2 = new ConcreteColleague2(m);
 
            m.Colleague1 = c1;
            m.Colleague2 = c2;
 
            c1.Send("How are you?");
            c2.Send("Fine, thanks");
 
            Console.ReadKey();
        }
    }
}
 
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
using System;
using System.Collections;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace CSharp_IteratorPattern
{
    abstract class Aggregate
    {
        public abstract Iterator CreateIterator();
    }
 
    class ConcreteAggregate : Aggregate
    {
        private ArrayList _items = new ArrayList();
 
        public override Iterator CreateIterator()
        {
            return new ConcreteIterator(this);
        }
 
        public int Count
        {
            get { return _items.Count; }
        }
 
        public object this[int index]
        {
            get { return _items[index]; }
            set { _items.Insert(index, value); }
        }
    }
 
    abstract class Iterator
    {
        public abstract object First();
        public abstract object Next();
        public abstract bool IsDone();
        public abstract object CurrentItem();
    }
 
    class ConcreteIterator : Iterator
    {
        private ConcreteAggregate _aggregate;
        private int _current = 0;
 
        public ConcreteIterator(ConcreteAggregate aggregate)
        {
            this._aggregate = aggregate;
        }
 
        public override object First()
        {
            return _aggregate[0];
        }
 
        public override object Next()
        {
            object ret = null;
            if (_current < _aggregate.Count - 1)
            {
                ret = _aggregate[++_current];
            }
 
            return ret;
        }
 
        public override object CurrentItem()
        {
            return _aggregate[_current];
        }
 
        public override bool IsDone()
        {
            return _current >= _aggregate.Count;
        }
    }
 
    class Program
    {
        static void Main(string[] args)
        {
            ConcreteAggregate a = new ConcreteAggregate();
            a[0= "Item A";
            a[1= "Item B";
            a[2= "Item C";
            a[3= "Item D";
 
            ConcreteIterator i = new ConcreteIterator(a);
 
            Console.WriteLine("Iterating over collection:");
 
            object item = i.First();
            while (item != null)
            {
                Console.WriteLine(item);
                item = i.Next();
            }
 
            Console.ReadKey();
        }
    }
}
 
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
66
67
using System;
 
namespace CSharp_CommandPattern
{    
    abstract class Command
    {
        protected Receiver receiver;
 
        public Command(Receiver receiver)
        {
            this.receiver = receiver;
        }
 
        public abstract void Execute();
    }
 
    class ConcreteCommand : Command
    {
        public ConcreteCommand(Receiver receiver) : base(receiver)
        {
        }
 
        public override void Execute()
        {
            receiver.Action();
        }
    }
 
    class Receiver
    {
        public void Action()
        {
            Console.WriteLine("Called Receiver.Action()");
        }
    }
 
    class Invoker
    {
        private Command _command;
 
        public void SetCommand(Command command)
        {
            this._command = command;
        }
 
        public void ExecuteCommand()
        {
            _command.Execute();
        }
    }
 
    class Program
    {
        static void Main()
        {
            Receiver receiver = new Receiver();
            Command command = new ConcreteCommand(receiver);
            
            Invoker invoker = new Invoker();
            invoker.SetCommand(command);
            invoker.ExecuteCommand();
 
            Console.ReadKey();
        }
    }
}
 
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace CSharp_DesignPattern
{
    abstract class Subject {
        public abstract void Request();
    }
 
    class RealSubject : Subject
    {
        public override void Request()
        {
            Console.WriteLine("Cakked RealSubject.Request");
        }
    }
 
    class Proxy : Subject
    {
        private RealSubject _realSubject;
 
        public override void Request()
        {
            if (_realSubject == null)
            {
                _realSubject = new RealSubject();
            }
 
            _realSubject.Request();
        }
    }
 
    class Program
    {
        static void Main(string[] args)
        {
            Proxy proxy = new Proxy();
            proxy.Request();
 
            Console.ReadKey();
        }
    }
}
 
 
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
66
67
68
69
70
71
72
73
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace CSharp_FacedePattern
{
    class SubSystemOne {
        public void MethodOne() {
            Console.WriteLine(" SubSystemOne Method");
        }
    }
 
    class SubSystemTwo {
        public void MethodTwo() {
            Console.WriteLine(" SubSystemTwo Method");
        }
    }
 
    class SubSystemThree {
        public void MethodThree() {
            Console.WriteLine(" SubSystemThree Method");
        }
    }
 
    class SubSystemFour {
        public void MethodFour() {
            Console.WriteLine(" SubSystemFour Method");
        }
    }
 
    class Facade {
        private SubSystemOne _one;
        private SubSystemTwo _two;
        private SubSystemThree _three;
        private SubSystemFour _four;
 
        public Facade() {
            _one = new SubSystemOne();
            _two = new SubSystemTwo();
            _three = new SubSystemThree();
            _four = new SubSystemFour();
        }
 
        public void MethodA() {
            Console.WriteLine("\nMethodA() ---- ");
            _one.MethodOne();
            _two.MethodTwo();
            _four.MethodFour();
        }
 
        public void MethodB() {
            Console.WriteLine("\nMethodB() ---- ");
            _two.MethodTwo();
            _three.MethodThree();
        }
    }
 
    class Program
    {
        static void Main(string[] args)
        {
            Facade facade = new Facade();
            facade.MethodA();
            facade.MethodB();
    
            Console.ReadKey();
        }
    }
}
 
 
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
66
67
68
69
70
71
72
73
74
75
76
77
78
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace CSharp_DecoratorPattern
{
    abstract class Component
    {
        public abstract void Operation();
    }
 
    class ConcreteComponent : Component
    {
        public override void Operation()
        {
            Console.WriteLine("ConcreteComponent.Operation()");
        }
    }
 
    abstract class Decorator : Component
    {
        protected Component component;
 
        public void SetComponent(Component component)
        {
            this.component = component;
        }
 
        public override void Operation()
        {
            if (component != null)
            {
                component.Operation();
            }
        }
    }
 
    class ConcreteDecoratorA : Decorator
    {
        public override void Operation()
        {
            base.Operation();
            Console.WriteLine("ConcreteDecoratorA.Operation()");
        }
    }
 
    class ConcreteDecoratorB : Decorator
    {
        public override void Operation()
        {
            base.Operation();
            AddedBehavior();
            Console.WriteLine("ConcreteDecoratorB.Operation()");
        }
 
        void AddedBehavior()
        {
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            ConcreteComponent c = new ConcreteComponent();
            ConcreteDecoratorA d1 = new ConcreteDecoratorA();
            ConcreteDecoratorB d2 = new ConcreteDecoratorB();
 
            d1.SetComponent(c);
            d2.SetComponent(d1);
 
            d2.Operation();
 
            Console.ReadKey();
        }
    }
}
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace CSharp_CompositePattern
{
    abstract class Component
    {
        protected string name;
 
        public Component(string name)
        {
            this.name = name;
        }
 
        public abstract void Add(Component c);
        public abstract void Remove(Component c);
        public abstract void Display(int depth);
    }
    
    class Composite : Component
    {
        private List<Component> _children = new List<Component>();
 
        public Composite(string name) : base(name)
        {
        }
 
        public override void Add(Component component)
        {
            _children.Add(component);
        }
 
        public override void Remove(Component component)
        {
            _children.Remove(component);
        }
 
        public override void Display(int depth)
        {
            Console.WriteLine(new String('-', depth) + name);
 
            foreach (Component component in _children)
            {
                component.Display(depth + 2);
            }
        }
    }
 
    class Leaf : Component
    {
        public Leaf(string name) : base(name)
        {
        }
 
        public override void Add(Component c)
        {
            Console.WriteLine("Cannot add to a leaf");
        }
 
        public override void Remove(Component c)
        {
            Console.WriteLine("Cannot remove from a leaf");
        }
 
        public override void Display(int depth)
        {
            Console.WriteLine(new String('-', depth) + name);
        }
    }
 
    class Program
    {
        static void Main(string[] args)
        {
            Composite root = new Composite("root");
            root.Add(new Leaf("Leaf A"));
            root.Add(new Leaf("Leaf B"));
 
            Composite comp = new Composite("Composite X");
            comp.Add(new Leaf("Leaf XA"));
            comp.Add(new Leaf("Leaf XB"));
 
            root.Add(comp);
            root.Add(new Leaf("Leaf C"));
 
            Leaf leaf = new Leaf("Leaf D");
            root.Add(leaf);
            root.Remove(leaf);
 
            root.Display(1);
 
            Console.ReadKey();
        }
    }
}
 
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
66
67
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace CSharp_BridgePattern
{
    class Abstraction
    {
        protected Implementor implementor;
 
        public Implementor Implementor
        {
            set { implementor = value; }
        }
 
        public virtual void Operation()
        {
            implementor.Operation();
        }
    }
    abstract class Implementor
    {
        public abstract void Operation();
    }
 
    class RefinedAbstraction : Abstraction
    {
        public override void Operation()
        {
            implementor.Operation();
        }
    }
 
    class ConcreteImplementorA : Implementor
    {
        public override void Operation()
        {
            Console.WriteLine("ConcreteImplementorA Operation");
        }
    }
 
    class ConcreteImplementorB : Implementor
    {
        public override void Operation()
        {
            Console.WriteLine("ConcreteImplementorB Operation");
        }
    }
 
    class Program
    {
        static void Main(string[] args)
        {
            Abstraction ab = new RefinedAbstraction();
 
            ab.Implementor = new ConcreteImplementorA();
            ab.Operation();
 
            ab.Implementor = new ConcreteImplementorB();
            ab.Operation();
 
            Console.ReadKey();
        }
    }
}
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace CSharp_AdapterPattern
{
    class Target
    {
        public virtual void Request()
        {
            Console.WriteLine("Called Target Request()");
        }
    }
 
    class Adapter : Target
    {
        private Adaptee _adaptee = new Adaptee();
 
        public override void Request()
        {
            _adaptee.SpecificRequest();
        }
    }
 
    class Adaptee
    {
        public void SpecificRequest()
        {
            Console.WriteLine("Called SpecificRequest()");
        }
    }
 
    class Program
    {
        static void Main()
        {
            Target target = new Adapter();
            target.Request();
 
            Console.ReadKey();
        }
    }
}
 
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace CSharp_Prototype
{
    abstract class Prototype
    {
        private string _id;
 
        public Prototype(string id)
        {
            this._id = id;
        }
        public string Id
        {
            get { return _id; }
        }
 
        public abstract Prototype Clone();
    }
 
    class ConcretePrototype1 : Prototype
    {
        public ConcretePrototype1(string id) : base(id)
        {
        }
 
        public override Prototype Clone()
        {
            return (Prototype)this.MemberwiseClone();
        }
    }
 
    class ConcretePrototype2 : Prototype
    {
        public ConcretePrototype2(string id) : base(id)
        {
        }
 
        public override Prototype Clone() {
            return (Prototype)this.MemberwiseClone();
        }
    }
 
    class Program {
        static void Main()
        {
            ConcretePrototype1 p1 = new ConcretePrototype1("I");
            ConcretePrototype1 c1 = (ConcretePrototype1)p1.Clone();
            Console.WriteLine("Cloned: {0}", c1.Id);
 
            ConcretePrototype2 p2 = new ConcretePrototype2("II");
            ConcretePrototype2 c2 = (ConcretePrototype2)p2.Clone();
            Console.WriteLine("Cloned: {0}", c2.Id);
 
            Console.ReadKey();
        }
    }   
}
 
 
cs






예제코드


namespace 대장간시스템
{
    class 장비
    {
        string 가루;
        string 정수;
        int 공격력;
        int 방어력;        

        public 장비() { }

        public void Set가루(string d) { 가루 = d; }
        public void Set정수(string s) { 정수 = s; }        
    }

    abstract class 생산슬롯
    {
        protected 장비 장비객체;

        public 생산슬롯() { }
        public 장비 Get장비() { return 장비객체; }
        public void 장비객체생성() { 장비객체 = new 장비(); }

        public abstract void Build가루();
        public abstract void Build정수();
        public abstract void Build옵션();
    }

    class 무기생산슬롯 : 생산슬롯
    {
        public override void Build가루()
        {
            장비객체.Set가루("붉은 영혼의 가루");
        }

        public override void Build정수()
        {
            장비객체.Set정수("못된 보스의 정수");
        }

        public override void Build옵션()
        {
            // 장비객체.공격력 = 랜덤생성;
        }
    }

    class 방어구생산슬롯 : 생산슬롯
    {
        public override void Build가루()
        {
            장비객체.Set가루("푸른 영혼의 가루");
        }

        public override void Build정수()
        {
            장비객체.Set정수("무지센 보스의 정수");
        }

        public override void Build옵션()
        {
            // 장비객체.방어력 = 랜덤생성;
        }
    }

    class 대장장이
    {
        private 생산슬롯 선택된생산슬롯;

        public void Set생산슬롯(생산슬롯 slot) { 선택된생산슬롯 = slot; }
        public 장비 Get장비() { return 선택된생산슬롯.Get장비(); }

        public void Construct장비()
        {
            선택된생산슬롯.장비객체생성();
            선택된생산슬롯.Build가루();
            선택된생산슬롯.Build정수();
            선택된생산슬롯.Build옵션();
        }        
    }


    class Program
    {
        static void Main(string[] args)
        {
            대장장이 히드리그 = new 대장장이();
            생산슬롯[] 생산슬롯들 =
            {
                new 무기생산슬롯(),
                new 방어구생산슬롯()
            };

            히드리그.Set생산슬롯(생산슬롯들[0]);
            히드리그.Construct장비();

            장비 제작한장비 = 히드리그.Get장비();
        }
    }
}








예제코드


namespace 스타크래프트II
{
    abstract class 유닛1
    {
    }

    class 마린 : 유닛1
    {

    }

    class 바이킹 : 유닛1
    {

    }

    abstract class 유닛2
    {
    }

    class 불곰 : 유닛2
    {

    }

    class 의료선 : 유닛2
    {

    }

    abstract class 건물
    {
        public abstract 유닛1 유닛생산1();
        public abstract 유닛2 유닛생산2();
    }

    class 병영 : 건물
    {
        public override 유닛1 유닛생산1()
        {
            return new 마린();            
        }

        public override 유닛2 유닛생산2()
        {
            return new 불곰();
        }
    }

    class 우주공항 : 건물
    {
        public override 유닛1 유닛생산1()
        {
            return new 바이킹();
        }

        public override 유닛2 유닛생산2()
        {
            return new 의료선();
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
        }
    }
}






예제코드

using System;
using System.Collections.Generic;

namespace FactoryMethodEx
{
    public enum EnemyType
    {
        Zombie,
        Slime
    }

    abstract class Enemy
    {
        protected EnemyType type;
        protected string name;
        protected int hp;
        protected int exp;

        protected void Attack() { }        
    }

    class Zombie : Enemy
    {
        public Zombie()
        {
            type = EnemyType.Zombie;
            name = "Zombie";
            hp = 100;
            exp = 50;

            Console.WriteLine("{0} : 출현!!", this.name);
        }
    }

    class Slime : Enemy
    {
        public Slime()
        {
            type = EnemyType.Slime;
            name = "Slime";
            hp = 200;
            exp = 15;

            Console.WriteLine("{0} : 출현!!", this.name);
        }
    }

    abstract class EnemyGenerator
    {
        private List<Enemy> _enemy = new List<Enemy>();
        public EnemyGenerator()
        {

        }

        public List<Enemy> Enemys
        {
            get { return _enemy; }
        }

        public abstract void CreateEnemys(); // Factory Method
    }

    class PatternAGenerator : EnemyGenerator
    {
        public override void CreateEnemys()
        {
            Enemys.Add(new Zombie());
            Enemys.Add(new Zombie());
            Enemys.Add(new Zombie());
            Enemys.Add(new Zombie());
            Enemys.Add(new Zombie());
            Enemys.Add(new Zombie());
            Enemys.Add(new Zombie());
            Enemys.Add(new Zombie());
        }
    }

    class PatternBGenerator : EnemyGenerator
    {
        public override void CreateEnemys()
        {
            Enemys.Add(new Slime());
            Enemys.Add(new Slime());
            Enemys.Add(new Slime());
            Enemys.Add(new Zombie());
            Enemys.Add(new Zombie());
            Enemys.Add(new Zombie());
            Enemys.Add(new Zombie());
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            EnemyGenerator[] enemyGenerators = new EnemyGenerator[2];
            enemyGenerators[0] = new PatternAGenerator();
            enemyGenerators[1] = new PatternBGenerator();

            enemyGenerators[1].CreateEnemys();

            Console.ReadKey();
        }
    }
}








예제코드

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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace CSharp_Singleton
{
    class OldSingleton
    {
        public string Name { get; set; }
 
        private static OldSingleton _instance;        
        protected OldSingleton()
        {
        }
 
        public static OldSingleton Instance()
        {
            if (_instance == null)
            {
                _instance = new OldSingleton();
            }
 
            return _instance;
        }
    }
 
    // 멀티 스레드 동작시 다른 곳에서 동시에 객체에 접근하는 것을 방지
    class NewSingleton 
    {
        public string Name { get; set; }
 
        private static NewSingleton _instance;        
        private static object syncLock = new object();
 
        protected NewSingleton()
        {
        }
 
        public static NewSingleton Instance()
        {
            if (_instance == null)
            {
                lock (syncLock)
                {
                    if (_instance == null)
                    {
                        _instance = new NewSingleton();
                    }
                }
            }
 
            return _instance;
        }
    }
 
    // C# 기능을 이용한 싱글턴 클래스의 최적화
    sealed class OptimizeSingleton
    {
        public string Name { get; set; }
 
        private static readonly OptimizeSingleton _instance = new OptimizeSingleton();
 
        private OptimizeSingleton()
        {            
        }
 
        public static OptimizeSingleton Instance()
        {
            return _instance;
        }
    }
 
    class Program
    {
        static void Main(string[] args)
        {
            OldSingleton os1 = OldSingleton.Instance();
            OldSingleton os2 = OldSingleton.Instance();
            os1.Name = "This is old singleton class!!";
            Console.WriteLine(os2.Name);
 
            NewSingleton ns1 = NewSingleton.Instance();
            NewSingleton ns2 = NewSingleton.Instance();
            ns1.Name = "This is new singleton class!!";
            Console.WriteLine(ns2.Name);
 
            OptimizeSingleton ops1 = OptimizeSingleton.Instance();
            OptimizeSingleton ops2 = OptimizeSingleton.Instance();
            ops1.Name = "This is new C# optimize singleton class!!";
            Console.WriteLine(ops2.Name);
            
            Console.ReadKey();
        }
    }
}
 
cs



+ Recent posts