1.单例模式...
Singleton pattern is one of the simplest design patterns.
This type of design pattern comes under creational pattern as this pattern provides one of the best ways to create an object.
This pattern involves a single class which is responsible to create an object while making sure that only single object gets created.
This class provides a way to access its only object which can be accessed directly without need to instantiate the object of the class.
2.adapter pattern
适配器模式——把一个类的接口变换成客户端所期待的另一种接口,从而使原本接口不匹配而无法一起工作的两个类能够在一起工作;
在类适配器模式中,适配器与适配者之间是继承(或实现)关系;
在对象适配器模式中,适配器与适配者之间是关联关系;
在实际开发中,对象适配器的使用频率更高;
下面是类适配器
下面有一个游戏机,一台电脑,电脑原本只能编辑文档不能玩游戏,但是通过适配器模式,现在的电脑已经可以玩游戏了
using System;
namespace Adapter_Pattern
{
class Program
{
//adapter pattern
static void Main(string[] args)
{
Dell dell = new Dell();
//Dell wanna Play the game!
dell.editWord();
}
//target role
public interface DellComputer
{
void editWord();
}
//need to adapted
public abstract class gameMachine
{
public void playGame()
{
Console.WriteLine("开始玩游戏了!");
}
}
public class Dell : gameMachine, DellComputer
{
public void editWord()
{
Console.WriteLine("我是戴尔!");
this.playGame();
}
}
}
}
输出:
对象适配器:对象适配器的使用频率更高 !
using System;
namespace Adapter_Pattern
{
class Program
{
//object adapter pattern
static void Main(string[] args)
{
//Dell wanna play the game!
//Dell can playing the game now!
DellAdapter dell = new DellAdapter();
Console.WriteLine("我是戴尔电脑!");
dell.editWord();
}
//target role
//DellComputer only edits the wordFile
public class DellComputer
{
public virtual void editWord() { }
}
//need to adapted
public class gameMachine
{
public void playGame()
{
Console.WriteLine("可以玩游戏了!");
}
}
public class DellAdapter : DellComputer
{
gameMachine _gameMachine = new gameMachine();
public override void editWord()
{
_gameMachine.playGame();
}
}
}
}