https://refactoring.guru/design-patterns/visitor
Visitor
Problem Imagine that your team develops an app which works with geographic information structured as one colossal graph. Each node of the graph may represent a complex entity such as a city, but also more granular things like industries, sightseeing areas,
refactoring.guru
데이터 기반의 객체가 존재하고 이를 최대한 수정하고 싶지 않다.
이때 이 객체들을 기반으로 여러가지 기능을 추가하고 싶을때, 기존 데이터 객체는 건드리지 않고 visitor 객체를 만들어 추가 기능을 구현한다.
데이터와 기능이 분리가 되며, 이럴때 visitor 패턴을 사용한다.
https://post.naver.com/viewer/postView.naver?volumeNo=33514945&memberNo=25379965&vType=VERTICAL
[Design pattern] 알아두면 유용한 9가지 GoF 디자인 패턴 정리
[BY 한빛미디어] 상황에 따라 유용하게 사용할 수 있는 9가지 GoF 디자인 패턴을 소개합니다. 각각의 패...
m.post.naver.com
예제 코드
더보기
public abstract class AComponent
{
public void accept(AVisitor visitor) { visitor.SetComponent(this); }
public abstract int GetData();
}
public abstract class AVisitor
{
protected AComponent _comp;
public void SetComponent(AComponent comp) { _comp = comp; }
public abstract void FuncA();
public abstract void FuncB();
}
// Adding minimized amount of fixes
public class City : AComponent
{
// Some city data.
//
public override int GetData() { return 2; }
}
public class Building : AComponent
{
// Some building data.
//
//
public override int GetData() { return 11; }
}
// Functions to implement.
public class CityFunc : AVisitor
{
public override void FuncA() { Console.WriteLine( _comp.GetData() ); }
public override void FuncB() { Console.WriteLine( _comp.GetData() ); }
}
public class BuildingFunc : AVisitor
{
public override void FuncA() { Console.WriteLine( _comp.GetData() ); }
public override void FuncB() { Console.WriteLine( _comp.GetData() ); }
}
internal class VisitorDemo
{
public void Run()
{
AComponent city = new City();
AComponent building = new Building();
AVisitor cityF = new CityFunc();
AVisitor buildingF = new BuildingFunc();
city.accept(cityF);
building.accept(buildingF);
cityF.FuncA();
buildingF.FuncA();
}
}
'Work & Programming > System Design' 카테고리의 다른 글
[Design] - 고찰. (0) | 2024.05.17 |
---|---|
[Behavioral Pattern] - Template Method (0) | 2024.05.16 |
[Behavioral Pattern] - Strategy (0) | 2024.05.16 |
[Behavioral Pattern] - State (0) | 2024.05.16 |
[Behavioral Pattern] - Observer (0) | 2024.05.16 |