Adapter ModeTo convert the interface of a class into another excuse that the customer wants. The adapter mode allows the classes that cannot work together due to incompatibility of interfaces to work together. The data and behavior of the system are correct, but when the excuse is not correct, we should consider using an adapter to match an original object out of the control scope with an interface. The adapter mode is mainly used to reuse some existing classes.
The following example describes how to enable Yao to play in the same team as other players. In fact, Yao Ming can do what other players can achieve (the interface achieves the same content, and the data and behavior comply with the requirements ), only the differences between culture and language (the expression in interface implementation is not in line with the actual scenario). A translation is required in the middle to enable the seamless cooperation between Yao Ming and other players.
Class design diagram:
Code
Class adapterpattern
{
Static void main (string [] AGS)
{
Forwards QF = new forwards ("Battier ");
Traslate TR = new traslate ("Yao Ming ");
QF. Attack ();
Tr. Attack ();
Tr. Defense ();
Console. readkey ();
}
}
/// <Summary>
/// Players
/// </Summary>
Abstract class player
{
Protected string name;
Public player (string player)
{
This. Name = player;
}
Public abstract void attack ();
Public abstract void defense ();
}
/// <Summary>
/// Forward
/// </Summary>
Class forwards: Player
{
Public forwards (string name)
: Base (name)
{
}
Public override void attack ()
{
Console. writeline ("{0} attack", name );
}
Public override void defense ()
{
Console. writeline ("{0} Defender", name );
}
}
/// <Summary>
/// Center
/// </Summary>
Class center: Player
{
Public Center (string name)
: Base (name)
{
}
Public override void attack ()
{
Console. writeline ("{0} attack", name );
}
Public override void defense ()
{
Console. writeline ("{0} Defender", name );
}
}
/// <Summary>
/// Foreign striker
/// </Summary>
Class foreignercenter
{
Public String fname;
Public void attack ()
{
Console. writeline ("Foreign center {0} attack", fname );
}
Public void defense ()
{
Console. writeline ("Foreign center {0} Defender", fname );
}
}
/// <Summary>
/// Translation
/// </Summary>
Class traslate: Player
{
Foreignercenter wjzf = new foreignercenter ();
Public traslate (string name)
: Base (name)
{
Wjzf. fname = Name;
}
Internal foreignercenter
{
Get
{
Throw new system. notimplementedexception ();
}
Set
{
}
}
Public override void attack ()
{
Wjzf. Attack ();
}
Public override void defense ()
{
Wjzf. Defense ();
}
}