Purpose:Separate the abstract part from its implementation part so that they can all change independently.
Implementation points:Separation and aggregation. Divides an object into two parts. They are maintained by aggregation.
UML:
Code:In this example, the electrical switch function is separated from the switch function to adapt to different changes.
Public Abstract Class SW
{
Public Abstract Void Openandclose ();
}
// Unidirectional Switch
Class Singlesw: SW
{
Public Override Void Openandclose ()
{
Console. writeline ( " This is a single switch! " );
}
}
// Bidirectional Switch
Class Doublesw: SW
{
Public Override Void Openandclose ()
{
Console. writeline ( " This is a double switch !! " );
}
}
Public Abstract Class El_device
{
Protected SW _ switcher;
Public SW switcher
{
Set {_ Switcher = Value ;}
}
Public Virtual Void Openandclose ()
{
_ Switcher. openandclose ();
}
}
// Refrigerator class, playing the role of bridging
Public Class Frigde: el_device
{
Public Override Void Openandclose ()
{
_ Switcher. openandclose ();
}
}
// ------------------------- Execute --------------------------
Class Program
{
Static Void Main ( String [] ARGs)
{
// Xinfei refrigerator is a one-way switch
El_device Xinfei = New Frigde ();
Xinfei. switcher = New Singlesw ();
// Midea refrigerator is a two-way switch
El_device Meidi = New Frigde ();
Meidi. switcher = New Doublesw ();
Xinfei. openandclose ();
Meidi. openandclose ();
Console. Readline ();
}
}