파사드 vs. 중재자
저는이 두 패턴의 차이점을 연구하고 있습니다.
나는 파사드가 서브 시스템에 대한 액세스를 캡슐화하고 중개자가 컴포넌트 간의 상호 작용을 캡슐화한다는 것을 이해합니다.
나는 서브 시스템 구성 요소가 파사드를 인식하지 못한다는 것을 이해합니다.
저는 현재 App.Config, SQL에 저장된 사용자 설정, 어셈블리 정보 등의 구성 정보를 검색하는 방법을 캡슐화하기 위해 파사드를 사용하고 있으며 서로 다른 창 양식 간의 탐색을위한 중재자를 사용하고 있습니다.
그러나 대부분의 사이트는 중재자가 "기능을 추가"한다고 지적합니다. 이것은 무엇을 의미합니까? 중재자는 기능을 어떻게 추가합니까?
... 대부분의 사이트는 중재자가 "기능을 추가"한다고 지적합니다 ...
외관 만 다른 관점에서 기존의 기능을 제공합니다.
중재자는 이 새로운 하나를 만들 수있는 다른 기존 기능을 결합하기 때문에 기능 "을 추가합니다."
다음 예를 살펴보십시오.
로깅 시스템이 있습니다. 해당 로깅 시스템에서 파일, 소켓 또는 데이터베이스에 로깅 할 수 있습니다.
파사드 디자인 패턴을 사용하면 파사드가 노출하는 단일 "인터페이스"뒤에있는 기존 기능의 모든 관계를 "숨길"수 있습니다.
클라이언트 코드 :
Logger logger = new Logger();
logger.initLogger("someLogger");
logger.debug("message");
구현에는 많은 개체의 상호 작용이 포함될 수 있습니다. 그러나 결국에는 기능이 이미 존재합니다. 아마도 "디버그"메서드는 다음과 같이 구현됩니다.
이행:
class Logger {
private LoggerImpl internalLogger;
private LoggerManager manager;
public void initLogger( String loggerName ) {
this.internalLogger = manager.getLogger( loggerName );
}
public void debug( String message ) {
this.internalLogger.debug( message );
}
}
기능이 이미 존재합니다. 정면은 그것을 숨길뿐입니다. 이 가상의 경우 LoggerManager는 올바른 로거의 생성을 처리하고 LoggerImpl은 "디버그"메소드가있는 패키지 개인용 객체입니다. 이런 식으로 Facade는 기능을 추가하지 않고 기존 개체에 위임하는 것입니다.
반면에 중재자는 다른 개체를 결합하여 새로운 기능을 추가합니다.
동일한 클라이언트 코드 :
Logger logger = new Logger();
logger.initLogger("someLogger");
logger.debug("message");
이행:
class Logger {
private java.io.PrintStream out;
private java.net.Socket client;
private java.sql.Connection dbConnection;
private String loggerName;
public void initLogger( String loggerName ) {
this.loggerName = loggerName;
if ( loggerName == "someLogger" ) {
out = new PrintStream( new File("app.log"));
} else if ( loggerName == "serverLog" ) {
client = new Socket("127.0.0.1", 1234 );
} else if( loggerName == "dblog") {
dbConnection = Class.forName()... .
}
}
public void debug( String message ) {
if ( loggerName == "someLogger" ) {
out.println( message );
} else if ( loggerName == "serverLog" ) {
ObjectOutputStrewam oos =
new ObjectOutputStrewam( client.getOutputStream());
oos.writeObject( message );
} else if( loggerName == "dblog") {
Pstmt pstmt = dbConnection.prepareStatment( LOG_SQL );
pstmt.setParameter(1, message );
pstmt.executeUpdate();
dbConnection.commit();
}
}
}
이 코드에서 중재자는 로그 할 적절한 "채널"을 만들고 해당 채널에 로그인 할 수있는 비즈니스 로직을 포함하는 것입니다. 중재자는 기능을 "만들고"있습니다.
Of course, there are better ways to implement this using polymorphism, but the point here is to show how the mediator "adds" new functionality by combining existing functionality ( in my sample didn't show very much sorry ) but imagine the mediator, read from the database the remote host where to log, then creates a client and finally write to that client print stream the log message. This way the mediator would be "mediating" between the different objects.
Finally, the facade is an structural pattern, that is it describes the composition of the objects, while the mediator is an behavioral, that is , it describes the way the objects interact.
I hope this helps.
I'm using mediator to add log file functionality.
It works like this:
- Obj A tells the mediator it needs something done.
- The mediator sends the message to various client objects.
- Obj B does the thing Obj A needs, and sends an appropriate message back via the mediator.
- Meanwhile, Obj C is also sent both messages by the mediator, and logs the results. That way, we can get user statistics from the log files.
- Obj D could be an error checker as well, so that if Obj B responds that Obj A's request is impossible, Obj D could be the thing that reports that to the user. Errors can now be logged in a different file than regular activity, and could use some other means to behave (beeping, whatever) that Obj A shouldn't really concern itself with.
under related patterns, gof says: Facade (185) differs from Mediator in that it abstracts a subsystem of objects to provide a more convenient interface. Its protocol is unidirectional; that is, Facade objects make requests of the subsystem classes but not vice versa. In contrast, Mediator enables cooperative behavior that colleague objects don't or can't provide, and the protocol is multidirectional.
Take a simple analogy:
Facade: like a parking lot, when call
parkingLot.Out(car1);
mab be a simple chain works:
{
car1.StartEngin();
attendant.charge();
car1.driverOut();
}
Mediator: like traffic light.
There are interactions between light and car,
and cars are controlled by it's state.
I though maybe this is the mediator “adds functionality”
And about the definition:
Facade's Type: Structural
Mediator's Type: Behavioral
facade more concerned about the components were contained in the unified interface,
and mediator concern how a set of objects interact.
I thought the distinction was directional: facade is a one-way communication between client and facade; mediator can be a two-way conversation, with messages flowing back and forth between the client and mediator.
From the "Design Patterns" book, the KEY of the Mediator pattern is described as follows: "It (a mediator) acts as a HUB of communication for widgets (i.e., 'a' group of interdependent objects)."
In other words, a mediator object is the sole superobject that knows all other objects in a group of collaborating objects and how they should interact with each other. All other objects should interact with the mediator object, instead of each other.
In contrast, a facade is a "unified interface" for a set of interfaces in a subsystem - for use by consumers of the subsystem - not among the components of the subsystem.
You can find details about Facade pattern in this SE question:
What is Facade Design Pattern?
Facade provides a simple and unified interface to complex system.
Real world example (cleartrip flight+hotel booking) is available in this post:
What is Facade Design Pattern?
Mediator pattern: Define an object that encapsulates how a set of objects interact. Mediator promotes loose coupling by keeping objects from referring to each other explicitly, and it lets you vary their interaction independently.
A real world example of Mesh network topology has been provided in below SE question:
Mediator Vs Observer Object-Oriented Design Patterns
Regarding your query on Mediator adds responsibility:
Facade provides only interface to existing sub-systems. Existing sub-systems are not aware of Facade class itself.
Mediator knows about colleague objects. It enables communication between different colleagues. In the example I have quoted in linked question, ConcreteMediator(NetworkMediator) sends notifications of register and unregister event of one colleague to all other colleagues.
Both impose some kind of policy on another group of objects. Facade imposes the policy from above, and Mediator imposes the policy from below. The use of Facade is visible and constraining, while the use of Mediator is invisible and enabling.
The Facade pattern is used when you want to provide a simple and specific interface to a group of objects that has a complex and general interface.
The Mediator pattern also imposes policy. However, whereas Facade imposed its policy in a visible and constraining way, Mediator imposes its policies in a hidden and unconstrained way.
Agile Software Development, Principles, Patterns, and Practices Robert C. Martin.
참고URL : https://stackoverflow.com/questions/481984/fa%c3%a7ade-vs-mediator
'Program Club' 카테고리의 다른 글
| 도메인 및 하위 도메인에 대한 자체 서명 된 인증서 만들기-NET :: ERR_CERT_COMMON_NAME_INVALID (0) | 2020.10.16 |
|---|---|
| Python에서 개체 목록 만들기 (0) | 2020.10.16 |
| Ruby 1.9 표준 CSV 라이브러리 란 무엇입니까? (0) | 2020.10.16 |
| Ruby 1.9 표준 CSV 라이브러리 란 무엇입니까? (0) | 2020.10.16 |
| ZeroMQ, RabbitMQ 및 Apache Qpid의 성능 비교 (0) | 2020.10.16 |