Using inheritance has the drawback that adding functionality requires changes in both the upper and lower layers. At the same time, it is necessary to avoid disclosing details to the outside world. Loose coupling should be maintained to prevent a static connection between the two.
There are interfaces and implementations as follows:
public interface ITest
{
void A();
void B();
}
public class T1 : ITest
{
public void A() { }
public void B() { }
}
public class T2 : ITest
{
public void A() { }
public void B() { }
}
Using the bridge pattern, a new class can be added as follows:
public class Client
{
private ITest _Implementor;
public ITest Implementor { get { return _Implementor; } set { _Implementor = value; } }
public virtual void A()
{
_Implementor.A();
}
public virtual void B()
{
_Implementor.B();
}
}
After instantiating the bridge type, it can be bridged to T1 or T2, and the usage is as follows:
class Program
{
static void Main(string[] args)
{
Client client = new Client();
client.Implementor = new T1();
client.A();
client.B();
client.Implementor = new T2();
client.A();
client.B();
}
}
The factory pattern is about providing instances, while the bridge pattern is about providing adaptation in structure.
The adapter pattern is somewhat similar to the bridge pattern.
文章评论