개발/기본) 디자인패턴
디자인패턴)더블 디스패치(Double Dispatch)
테샤르
2023. 7. 31. 08:16
더블 디스패치(Double Dispatch)
이 패턴은 둘 이상의 개체 유형에 따라 다르게 동작해야 하는 작업이 있는 경우 특히 유용하다고한다.
단일 디스패치의 단점을 보완했다.
<예시코드>
public interface IShape
{
void Accept(IShapeVisitor visitor);
}
public class Circle : IShape
{
public void Accept(IShapeVisitor visitor)
{
visitor.Visit(this);
}
}
public class Square : IShape
{
public void Accept(IShapeVisitor visitor)
{
visitor.Visit(this);
}
}
public interface IShapeVisitor
{
void Visit(Circle circle);
void Visit(Square square);
}
public class ShapeTypePrinter : IShapeVisitor
{
public void Visit(Circle circle)
{
Console.WriteLine("This is a circle");
}
public void Visit(Square square)
{
Console.WriteLine("This is a square");
}
}
< 실제 사용 예시>
IShape shape1 = new Circle();
IShape shape2 = new Square();
IShapeVisitor printer = new ShapeTypePrinter();
shape1.Accept(printer); // prints "This is a circle"
shape2.Accept(printer); // prints "This is a square"
반응형
더블 디스패처 패턴을 사용하게되면 복잡한 유형 검사 및 캐스팅을 피하고 코드를 보다 유연하고
유지 관리하기 쉽게 만드는 데 도움이 될 수 있다.
그러나 코드의 복잡성을 증가시키고 이해하기 어렵게 만들 수도 있으므로 신중하게 사용해야 한다.
참고링크 Double Dispatch in C# and DDD : [링크]
Double Dispatch in C# and DDD
Double dispatch is a pattern you can use in C# to control how communication flows between two objects.
ardalis.com
★☆☆☆☆
반응형