포스트

Strategy Pattern

Strategy Pattern

머리말


Strategy Pattern


Code Block


팩토리 패턴과 함께 이런식으로 쓸 수 있다.

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
public abstract class SomeStrategy
{
    public abstract void CreateSomeThing(ref SomeObject someObject);
}

public class SomeStrategyA: SomeStrategy
{
    public SomeStrategyA() { /* Constructor */ }

    public override void CreateSomeThing(ref SomeObject someObject)
    {
        someObject = new SomeObjectA();
    }
}

public class SomeClassB: SomeStrategy
{
    private SomeVariable someVariable; // Only for SomeClassB

    public SomeClassB(int a, int b)
    {
        someVariable = new SomeVariable();
    }

    public override void CreateSomeThing(ref SomeObject someObject)
    {
        someObject = new SomeObjectB();
    }
}

public class SomeFactory
{
    public SomeStrategy CreateSomeStrategy() => someEnum switch
    {
        SomeEnum.A => new SomeStrategyA(),
        SomeEnum.B => new SomeStrategyB(1, 2),
        _ => throw new ArgumentOutOfRangeException(nameof(someEnum), someEnum, null)
    };
}
이 기사는 저작권자의 CC BY 4.0 라이센스를 따릅니다.