单例模式 (Singleton)

单例讲的是当一个类被初次调用时,会产生一个类的实例, 而这个类的实例会贯穿程序的整个生命周期。单例提供了一个全局、唯一的实例。
步骤:1.让类自己创建一个实例;2.提供一个全局访问这个实例的方法;3.声明这个类的构造为私有,防止其他对象创建一个新实例。

C#示例:

    public   class Singleton

    {

        private static Singleton instance;

        private Singleton()

        {

        }

 

        public static Singleton CreateInstance()

        {

            if (instance == null)

            {

                instance = new Singleton(); 

            }

            return instance;

        }

    }

}



适配器模式  (Adapter)

适配器讲的是当现有已存在的类不符合新环境的接口时,需要复用现有代码。适配器模式有类适配器和对象适配器。

类适配器
用包装类(所谓的适配器)继承新环境的接口和旧类,在类适配器中实现现有接口,实现时直接在接口方法里调用或者包装旧类的方法。

C#示例:
public class OldPower
{
     public void GetPower220v()
     {
          Console.WriteLine("220v power.");
     }
}

public interface IPower
{
void GetPower();
}

public class Adapter :  IPower, OldPower
{
     public void GetPower()
     {
          return base.GetPower220v();
     }
}

//Use
public class Program
{
     void Main(string[] Args)
     {
          IPower p = new Adapter();
          p.GetPower();         
     }
}

对象适配器
用包装类(适配器)继承新环境的接口,在类适配器中实例化旧类,实现接口时在接口方法里调用或者包装已经实例化的旧类对象的方法。

C#示例:
public class OldPower
{
     public void GetPower220v()
     {
     ///
     }
}

public interface IPower
{
void GetPower();
}

public class ObjectAdapter : IPower
{
     private Power _p = new Power();
    
     public void GetPower()
     {
          if (null != _p)
          {
               _p.GetPower220v();
          }
     }
}

//Use
public class Program
{
     void Main(string[] Args)
     {
          IPower p = new Adapter();
          p.GetPower();         
     }
}

平时建议尽量用对象适配器而不是类适配器, 因为类适配器的多继承可能引进一些不必要的东西。对象适配器更加松耦合。




相关文章:

  • 2022-01-06
  • 2021-10-26
  • 2021-06-24
  • 2021-09-10
  • 2021-12-05
  • 2021-06-14
猜你喜欢
  • 2021-11-05
  • 2021-09-18
  • 2021-12-21
  • 2022-12-23
  • 2021-08-14
  • 2021-07-14
  • 2021-08-17
相关资源
相似解决方案