전략 패턴은 어떻게 작동합니까?
어떻게 작동하며 어떤 용도로 사용되며 언제 사용해야합니까?
전략 패턴을 쉬운 방법으로 설명하겠습니다.
Car()
메서드 가있는 클래스 가 run()
있으므로 의사 언어에서 다음과 같이 사용합니다.
mycar = new Car()
mycar.run()
이제 run()
프로그램이 실행되는 동안 즉시 동작 을 변경할 수 있습니다 . 예를 들어, 모터 장애 또는 비디오 게임에서 "부스트"버튼 사용을 시뮬레이션 할 수 있습니다.
이 시뮬레이션을 수행하는 방법에는 여러 가지가 있습니다. 조건문과 플래그 변수를 사용하는 것이 한 가지 방법입니다. 전략 패턴은 또 다른 것입니다. run()
메서드 의 동작 을 다른 클래스에 위임합니다 .
Class Car()
{
this.motor = new Motor(this)
// passing "this" is important for the motor so it knows what it is running
method run()
{
this.motor.run()
}
method changeMotor(motor)
{
this.motor = motor
}
}
자동차의 동작을 바꾸고 싶다면 모터 만 바꾸면됩니다. (실생활보다 프로그램이 더 쉬웠 죠? ;-))
복잡한 상태가 많은 경우 매우 유용합니다. 훨씬 쉽게 변경하고 유지할 수 있습니다.
문제
전략 패턴은 다른 전략에 의해 구현되거나 해결 될 수있는 (또는 예상되는) 문제를 해결하는 데 사용되며 이러한 경우에 대해 명확하게 정의 된 인터페이스를 보유합니다. 각 전략은 자체적으로 완벽하게 유효하며 일부 전략은 런타임 중에 애플리케이션이 전환 할 수있는 특정 상황에서 선호됩니다.
코드 예
namespace StrategyPatterns
{
// Interface definition for a Sort algorithm
public interface ISort
{
void Sort(List<string> list)
}
// QuickSort implementation
public class CQuickSorter : ISort
{
void Sort(List<string> list)
{
// Here will be the actual implementation
}
}
// BubbleSort implementation
public class CBubbleSort : ISort
{
void Sort(List<string> list)
{
// The actual implementation of the sort
}
}
// MergeSort implementation
public class CMergeSort : ISort
{
void Sort(List<string> list)
{
// Again the real implementation comes here
}
}
public class Context
{
private ISort sorter;
public Context(ISort sorter)
{
// We pass to the context the strategy to use
this.sorter = sorter;
}
public ISort Sorter
{
get{return sorter;)
}
}
public class MainClass
{
static void Main()
{
List<string> myList = new List<string>();
myList.Add("Hello world");
myList.Add("Another item");
myList.Add("Item item");
Context cn = new Context(new CQuickSorter());
// Sort using the QuickSort strategy
cn.Sorter.Sort(myList);
myList.Add("This one goes for the mergesort");
cn = new Context(new CMergeSort());
// Sort using the merge sort strategy
cn.Sorter.Sort(myList);
}
}
}
- 전략이란 무엇입니까? 전략은 특정 목표를 달성하기 위해 고안된 행동 계획입니다.
- “알고리즘 제품군을 정의하고 각 알고리즘을 캡슐화하여 상호 교환 가능하게 만드십시오. 전략을 사용하면 알고리즘이이를 사용하는 클라이언트와 독립적으로 달라질 수 있습니다. " (Gang of Four);
- Specifies a set of classes, each representing a potential behaviour. Switching between those classes changes the application behaviour. (the Strategy);
- This behaviour can be selected at runtime (using polymorphism) or design time;
- Capture the abstraction in an interface, bury implementation details in derived classes;
- An alternative to the Strategy is to change the application behaviour by using conditional logic. (BAD);
Using this pattern makes it easier to add or remove specific behaviour, without having to recode and retest, all or parts of the application;
Good uses:
- When we have a set of similar algorithms and its need to switch between them in different parts of the application. With Strategy Pattern is possible to avoid ifs and ease maintenance;
- When we want to add new methods to superclass that don’t necessarily make sense to every subclass. Instead of using an interface in a traditional way, adding the new method, we use an instance variable that is a subclass of the new Functionality interface. This is known as Composition : Instead of inheriting an ability through inheritance the class is composed with Objects with the right ability;
A closely related pattern is the Delegate pattern; in both cases, some of the work is passed to some other component. If I understand correctly, the difference between these patterns is this (and please correct me if I'm wrong):
In the Delegate pattern, the delegate is instantiated by the enclosing (delegating) class; this allows for code reuse by composition rather than inheritance. The enclosing class may be aware of the delegate's concrete type, e.g. if it invokes its constructor itself (as opposed to using a factory).
In the Strategy pattern, the component that executes the strategy is a dependency provided to the enclosing (using) component via its constructor or a setter (according to your religion). The using component is totally unaware of what strategy is in use; the strategy is always invoked via an interface.
Anyone know any other differences?
Directly from the Strategy Pattern Wikipedia article:
The strategy pattern is useful for situations where it is necessary to dynamically swap the algorithms used in an application. The strategy pattern is intended to provide a means to define a family of algorithms, encapsulate each one as an object, and make them interchangeable. The strategy pattern lets the algorithms vary independently from clients that use them.
To add to the already magnificient answers: The strategy pattern has a strong similarity to passing a function (or functions) to another function. In the strategy this is done by wrapping said function in an object followed by passing the object. Some languages can pass functions directly, so they don't need the pattern at all. But other languages can't pass functions, but can pass objects; the pattern then applies.
Especially in Java-like languages, you will find that the type zoo of the language is pretty small and that your only way to extend it is by creating objects. Hence most solutions to problems is to come up with a pattern; a way to compose objects to achieve a specific goal. Languages with richer type zoos often have simpler ways of going about the problems -- but richer types also means you have to spend more time learning the type system. Languages with dynamic typing discipline often gets a sneaky way around the problem as well.
참고URL : https://stackoverflow.com/questions/91932/how-does-the-strategy-pattern-work
'code' 카테고리의 다른 글
Python에서 로그 파일을 추적하려면 어떻게해야합니까? (0) | 2020.11.23 |
---|---|
libXtst.so.6을 찾거나 설치할 수 없습니까? (0) | 2020.11.23 |
mstest.exe는 어디에 있습니까? (0) | 2020.11.23 |
Linux의 PHP에서 --enable-soap을 어떻게 활성화합니까? (0) | 2020.11.23 |
Django 오류-일치하는 쿼리가 없습니다. (0) | 2020.11.23 |