C#设计模式之行为型模式的示例分析|c#设计模式有哪些

这篇文章给大家分享的是有关C#设计模式之行为型模式的示例分析的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。这里列举行为型模式·到此23种就列完了···这里是看着菜鸟教程来实现··,他里边列了25种,其中过滤器模式。

这篇文章给大家分享的是有关C#设计模式之行为型模式的示例分析的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。

这里列举行为型模式·到此23种就列完了···这里是看着菜鸟教程来实现··,他里边列了25种,其中过滤器模式和空对象模式应该不属于所谓的23种模式

责任链模式:为请求创建一个接收者对象的链,对请求的发送者和接收者进行解耦,大部分用于web中吧。。
Task中的continuewith和微软的tpl数据流应该是类似这种模式的实现吧

usingSystem;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Text;
usingSystem.Threading.Tasks;
//责任链模式
namespaceExercisePrj.Dsignmode
{
pubpcabstractclassAbstractLogger
{
pubpcstaticintINFO=1;
pubpcstaticintDEBUG=2;
pubpcstaticintERROR=3;
protectedintlevel;
//责任链中的下一个对象
protectedAbstractLoggernextLogger;
pubpcvoidSetNextLogger(AbstractLoggernext)
{
nextLogger=next;
}
pubpcvoidLogMessage(intlevel,stringmessage)
{
if(this.level<=level)
{
Write(message);
}
if(nextLogger!=null)
{
nextLogger.LogMessage(level,message);
}
}
protectedabstractvoidWrite(stringmessage);
}
pubpcclassConsoleLogger:AbstractLogger
{

pubpcConsoleLogger(intlevel)
{
this.level=level;
}

protectedoverridevoidWrite(stringmessage)
{
Console.WriteLine("StandardConsole::Logger:"+message);
}
}
pubpcclassErrorLogger:AbstractLogger
{

pubpcErrorLogger(intlevel)
{
this.level=level;
}

protectedoverridevoidWrite(Stringmessage)
{
Console.WriteLine("ErrorConsole::Logger:"+message);
}
}
pubpcclassFileLogger:AbstractLogger
{
pubpcFileLogger(intlevel)
{
this.level=level;
}

protectedoverridevoidWrite(Stringmessage)
{
Console.WriteLine("File::Logger:"+message);
}
}
}

命令模式(Command Pattern):请求以命令的形式执行,CAD的的命令应该就是以这种方式执行的·二次开发的时候通过特性标识和继承他的接口来添加命令,非常方便

usingSystem;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Text;
usingSystem.Threading.Tasks;
//命令模式
namespaceExercisePrj.Dsignmode
{
pubpcinterfaceIOrder
{
voidExecute();
}
pubpcclassStock
{
privatestringname="ABC";
privateintquantity=10;

pubpcvoidBuy()
{
Console.WriteLine("Stockname:{0},quantity:{1},bought",name,quantity);
}
pubpcvoidSell()
{
Console.WriteLine("Stockname:{0},quantity:{1}sold",name,quantity);
}
}
//请求类
pubpcclassBuyStock:IOrder
{
privateStockabcStock;

pubpcBuyStock(StockabcStock)
{
this.abcStock=abcStock;
}

pubpcvoidExecute()
{
abcStock.Buy();
}
}
//继承接口的实体
pubpcclassSellStock:IOrder
{
privateStockabcStock;

pubpcSellStock(StockabcStock)
{
this.abcStock=abcStock;
}

pubpcvoidExecute()
{
abcStock.Sell();
}
}

//命令调用类
pubpcclassBroker
{
privateList<IOrder>orderList=newList<IOrder>();

pubpcvoidtakeOrder(IOrderorder)
{
orderList.Add(order);
}

pubpcvoidplaceOrders()
{
foreach(IOrderorderinorderList)
{
order.Execute();
}
orderList.Clear();
}
}

}

解释器模式:就是实现一种表达式接口,C#的各种表达式就是这种实现吧··这玩意跟富文本编辑器一样是个大坑吧··,做好了确实很好使,一不小心就得跪

usingSystem;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Text;
usingSystem.Threading.Tasks;
//解释器模式
namespaceExercisePrj.Dsignmode
{
pubpcinterfaceExpression
{
boolInterpret(stringcontext);
}
pubpcclassTerminalExpression:Expression
{
privatestringdata;

pubpcTerminalExpression(stringdata)
{
this.data=data;
}

pubpcboolInterpret(stringcontext)
{
if(context.Contains(data))
{
returntrue;
}
returnfalse;
}
}
pubpcclassOrExpression:Expression
{
privateExpressionexpr1=null;
privateExpressionexpr2=null;
pubpcOrExpression(Expressionexpr1,Expressionexpr2)
{
this.expr1=expr1;
this.expr2=expr2;
}
pubpcboolInterpret(Stringcontext)
{
returnexpr1.Interpret(context)||expr2.Interpret(context);
}
}
pubpcclassAndExpression:Expression
{
privateExpressionexpr1=null;
privateExpressionexpr2=null;

pubpcAndExpression(Expressionexpr1,Expressionexpr2)
{
this.expr1=expr1;
this.expr2=expr2;
}
pubpcboolInterpret(Stringcontext)
{
returnexpr1.Interpret(context)&&expr2.Interpret(context);
}
}
}

迭代器模式(Iterator Pattern):.NET自带接口···,直接实现就行了··注意又泛型接口和非泛型接口··非泛型接口迭代对象返回的是object,泛型接口返回的直接就是对象了,还有通过yield的简化写法不用额外去实现IEnumerator接口

usingSystem;
usingSystem.Collections;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Text;
usingSystem.Threading.Tasks;

namespaceExercisePrj.Dsignmode
{
pubpcclassIteratorEx:IEnumerable//<IteratorEx>
{
pubpcstringName;
privateList<IteratorEx>pst=newList<IteratorEx>();

//pubpcIEnumerator<IteratorEx>GetEnumerator()
//{
//foreach(varpnpst)
//{
//yieldreturnl;
//}
//}

pubpcvoidSetList(List<IteratorEx>data)
{
pst=data;
}

IEnumeratorIEnumerable.GetEnumerator()
{
foreach(varpnpst)
{
yieldreturnl;
}
//returnnewIteratorExEnum(pst.ToArray());
}
}
pubpcclassIteratorExEnum:IEnumerator
{
privateIteratorEx[]pst;
privateintposition=-1;
pubpcIteratorExEnum(IteratorEx[]data)
{
pst=data;
}
pubpcobjectCurrent
{
get
{
try
{
returnpst[position];
}
catch(IndexOutOfRangeException)
{
thrownewInvapdOperationException();
}
}
}

pubpcboolMoveNext()
{
position++;
returnposition<pst.Length;
}

pubpcvoidReset()
{
position=-1;
}
}

}

中介者模式(Mediator Pattern):用一个中介对象封装一些对象的交互,中介者使对象不用显式的互相引用,MVC和mvp 的c和p都是类似这玩意的实现吧

usingSystem;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Text;
usingSystem.Threading.Tasks;

namespaceExercisePrj.Dsignmode
{
//中介类
pubpcclassChatRoom
{
pubpcstaticvoidShowMessage(Useruser,stringmsg)
{
Console.WriteLine(newDateTime().ToString()+"["+user.Name+"]:"+msg);
}
}
pubpcclassUser
{
pubpcstringName{get;set;}

pubpcUser(stringname)
{
Name=name;
}

pubpcvoidSendMessage(Stringmessage)
{
ChatRoom.ShowMessage(this,message);
}
}


}

备忘录模式(Memento Pattern):在不破坏封装的前提下,捕获一个对象的内部状态,并在对象之外保存,

大部分支持回退的操作场景下应该都是这种模式··之前做的软件中有画图的操作···支持后退,实现方式非常简单粗暴··,直接吧图层的画图对象克隆一份保存··只支持5还是10步,讲道理这么实现确实有点那啥了···

usingSystem;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Text;
usingSystem.Threading.Tasks;

namespaceExercisePrj.Dsignmode
{
pubpcclassMemento
{
pubpcstringState{get;}
pubpcMemento(stringstate)
{
State=state;
}
}
pubpcclassOriginator
{
pubpcstringState{get;set;}

pubpcMementoSaveStateToMemento()
{
returnnewMemento(State);
}

pubpcvoidGetStateFromMemento(MementoMemento)
{
State=Memento.State;
}
}
pubpcclassCareTaker
{
privateList<Memento>mementoList=newList<Memento>();

pubpcvoidAdd(Mementostate)
{
mementoList.Add(state);
}

pubpcMementoGet(intindex)
{
returnmementoList[index];
}
}

}

观察者模式(Observer Pattern):.net自带的有接口提供来实现观察者模式···这里照着msdn来实现一遍,自带的接口里边还实现了资源的释放··,之前并发编程里边的rx也是这个模式的具体实现·

usingSystem;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Text;
usingSystem.Threading.Tasks;

//观察者模式
namespaceExercisePrj.Dsignmode
{

pubpcclassSubject:IObservable<Subject>
{
pubpcintState{get;set;}
pubpcSubject(intstate)
{
State=state;
}
privateList<IObserver<Subject>>observers=newList<IObserver<Subject>>();

pubpcIDisposableSubscribe(IObserver<Subject>observer)
{
if(!observers.Contains(observer))
observers.Add(observer);
returnnewUnsubscriber(observers,observer);
}
privateclassUnsubscriber:IDisposable
{
privateList<IObserver<Subject>>_observers;
privateIObserver<Subject>_observer;

pubpcUnsubscriber(List<IObserver<Subject>>observers,IObserver<Subject>observer)
{
this._observers=observers;
this._observer=observer;
}

pubpcvoidDispose()
{
if(_observer!=null&&_observers.Contains(_observer))
_observers.Remove(_observer);
}
}

pubpcvoidTrackLocation(Subjectob)
{
Console.WriteLine("start");
foreach(varobserverinobservers)
{
if(ob==null)
observer.OnError(newException("unknowExeption"));
else
observer.OnNext(ob);
}
}

pubpcvoidEndTransmission()
{
foreach(varobserverinobservers.ToArray())
if(observers.Contains(observer))
observer.OnCompleted();

observers.Clear();
}

}


pubpcclassBinaryObserver:IObserver<Subject>
{
pubpcvoidOnCompleted()
{
Console.WriteLine("complete");
}

pubpcvoidOnError(Exceptionerror)
{
Console.WriteLine(error.Message);
}

pubpcvoidOnNext(Subjectvalue)
{
Console.WriteLine("BinaryString:"+Convert.ToString(value.State,2));
}
}
pubpcclassOctalObserver:IObserver<Subject>
{
pubpcvoidOnCompleted()
{
Console.WriteLine("complete");
}

pubpcvoidOnError(Exceptionerror)
{
Console.WriteLine(error.Message);
}

pubpcvoidOnNext(Subjectvalue)
{
Console.WriteLine("OctalString:"+Convert.ToString(value.State,8));
}

}
pubpcclassHexaObserver:IObserver<Subject>
{
pubpcvoidOnCompleted()
{
Console.WriteLine("complete");
}

pubpcvoidOnError(Exceptionerror)
{
Console.WriteLine(error.Message);
}

pubpcvoidOnNext(Subjectvalue)
{
Console.WriteLine("HexString:"+Convert.ToString(value.State,16));
}
}
}

状态模式(State Pattern):当对象内部状态发生改变时,行为也跟着改变

这个模式是为了解决类里边的大量if和swicth语句,讲道理例子写的有点怪···主体是context

usingSystem;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Text;
usingSystem.Threading.Tasks;

namespaceExercisePrj.Dsignmode
{
pubpcclassContext
{
pubpcStateState{get;set;}

pubpcContext()
{
State=null;
}
}
pubpcinterfaceState
{
voidDoAction(Contextcontext);
}

pubpcclassStartState:State
{
pubpcvoidDoAction(Contextcontext)
{
Console.WriteLine("Playerisinstartstate");
context.State=this;
}

pubpcoverridestringToString()
{
return"StartState";
}
}
pubpcclassStopState:State
{

pubpcvoidDoAction(Contextcontext)
{
Console.WriteLine("Playerisinstopstate");
context.State=this;
}

pubpcoverridestringToString()
{
return"StopState";
}
}
}

空对象模式(Null Object Pattern):就是吧对空值的判断定义一个啥也不做的实体对象出来··C#的Nullable就是这个的实现···这玩意不在23种设计模式里边···

usingSystem;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Text;
usingSystem.Threading.Tasks;

namespaceExercisePrj.Dsignmode
{
pubpcabstractclassAbstractCustomer
{
pubpcabstractboolIsNull();
pubpcabstractstringName{get;}
}
pubpcclassRealCustomer:AbstractCustomer
{
pubpcoverridestringName{get;}

pubpcRealCustomer(stringname)
{
Name=name;
}
pubpcoverrideboolIsNull()
{
returnfalse;
}
}
pubpcclassNullCustomer:AbstractCustomer
{
pubpcoverridestringName{get{return"NotAvailableinCustomerDatabase";}}
pubpcoverrideboolIsNull()
{
returntrue;
}
}
pubpcclassCustomerFactory
{
pubpcstaticstring[]names={"Rob","Joe","Jupe"};
pubpcstaticAbstractCustomergetCustomer(stringname)
{
if(names.Contains(name))
{
returnnewRealCustomer(name);
}
returnnewNullCustomer();
}
}
}

策略模式(Strategy Pattern):定义一系列算法,封装成类,可以相互替换,通过构造不同的类,执行不同的操作。这样做方便调用,添加新的算法也方便,

最后加了自己之前对这个模式的奇葩写法

usingSystem;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Reflection;
usingSystem.Text;
usingSystem.Threading.Tasks;

namespaceExercisePrj.Dsignmode
{
pubpcinterfaceIStrategy
{
intDoOperation(intnum1,intnum2);
}
pubpcclassOperationAdd:IStrategy
{

pubpcintDoOperation(intnum1,intnum2)
{
returnnum1+num2;
}
}

pubpcclassOperationSubstract:IStrategy
{

pubpcintDoOperation(intnum1,intnum2)
{
returnnum1-num2;
}
}
pubpcclassOperationMultiply:IStrategy
{

pubpcintDoOperation(intnum1,intnum2)
{
returnnum1*num2;
}
}

pubpcclassContextEx
{
privateIStrategystrategy;

pubpcContextEx(IStrategystrategy)
{
this.strategy=strategy;
}

pubpcintExecuteStrategy(intnum1,intnum2)
{
returnstrategy.DoOperation(num1,num2);
}

//奇葩的写法简单粗暴
privateDictionary<string,Func<int,int,int>>funcs=newDictionary<string,Func<int,int,int>>();
pubpcintExecuteStrategy(stringname,intnum1,intnum2)
{
if(funcs.Count==0)
{
//反射写法
varassembly=Assembly.GetExecutingAssembly();
vartypes=assembly.GetTypes();
foreach(vartintypes)
{
if(t.GetInterface("IStrategy")!=null)
{
varinstance=assembly.CreateInstance(t.FullName)asIStrategy;
funcs.Add(t.Name,instance.DoOperation);
}
}
//直接添加
//funcs.Add("OperationAdd",newFunc<int,int,int>((n1,n2)=>{returnn1+n2;}));
//funcs.Add("OperationSubstract",newFunc<int,int,int>((n1,n2)=>{returnn1-n2;}));
//funcs.Add("OperationMultiply",newFunc<int,int,int>((n1,n2)=>{returnn1*n2;}));
}
returnfuncs[name](num1,num2);
}


}
}

模板模式(Template Pattern):.net的泛型就是这个模式的实现吧··照着模子写就行了

usingSystem;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Text;
usingSystem.Threading.Tasks;

namespaceExercisePrj.Dsignmode
{
pubpcabstractclassGame
{
pubpcabstractvoidInitiapze();
pubpcabstractvoidStartPlay();
pubpcabstractvoidEndPlay();

//模板
pubpcvoidplay()
{

//初始化游戏
Initiapze();
//开始游戏
StartPlay();
//结束游戏
EndPlay();
}
}
pubpcclassCricket:Game
{
pubpcoverridevoidEndPlay()
{
Console.WriteLine("CricketGameFinished!");
}

pubpcoverridevoidInitiapze()
{
Console.WriteLine("CricketGameInitiapzed!Startplaying.");
}


pubpcoverridevoidStartPlay()
{
Console.WriteLine("CricketGameStarted.Enjoythegame!");
}
}
}

访问者模式(Visitor Pattern):在被访问的类里边加一个对外提供接待访问的接口
把数据结构和对应的操作分开·添加操作很容易,但是如果结构变化多的化,改起来就麻烦了··
没研究没用过····

usingSystem;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Text;
usingSystem.Threading.Tasks;

namespaceExercisePrj.Dsignmode
{

pubpcinterfaceIComputerPartVisitor
{
voidVisit(Computercomputer);
voidVisit(Mousemouse);
voidVisit(Keyboardkeyboard);
voidVisit(Monitormonitor);
}

pubpcinterfaceIComputerPart
{
voidAccept(IComputerPartVisitorcomputerPartVisitor);
}

pubpcclassKeyboard:IComputerPart
{

pubpcvoidAccept(IComputerPartVisitorcomputerPartVisitor)
{
computerPartVisitor.Visit(this);
}
}
pubpcclassMonitor:IComputerPart
{

pubpcvoidAccept(IComputerPartVisitorcomputerPartVisitor)
{
computerPartVisitor.Visit(this);
}
}
pubpcclassMouse:IComputerPart
{
pubpcvoidAccept(IComputerPartVisitorcomputerPartVisitor)
{
computerPartVisitor.Visit(this);
}
}
pubpcclassComputer:IComputerPart
{
IComputerPart[]parts;
pubpcComputer()
{
parts=newIComputerPart[]{newMouse(),newKeyboard(),newMonitor()};
}
pubpcvoidAccept(IComputerPartVisitorcomputerPartVisitor)
{
for(inti=0;i<parts.Length;i++)
{
parts[i].Accept(computerPartVisitor);
}
computerPartVisitor.Visit(this);
}
}

pubpcclassComputerPartDisplayVisitor:IComputerPartVisitor
{
pubpcvoidVisit(Computercomputer)
{
Console.WriteLine("DisplayingComputer.");
}
pubpcvoidVisit(Mousemouse)
{
Console.WriteLine("DisplayingMouse.");
}
pubpcvoidVisit(Keyboardkeyboard)
{
Console.WriteLine("DisplayingKeyboard.");
}
pubpcvoidVisit(Monitormonitor)
{
Console.WriteLine("DisplayingMonitor.");
}
}
}

感谢各位的阅读!关于“C#设计模式之行为型模式的示例分析”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!

C#设计模式之行为型模式的示例分析的介绍就聊到这里吧,感谢你花时间阅读,更多关于C#设计模式之行为型模式的示例分析的信息别忘了在本站进行查找哦。屹东网往后会继续推荐C#设计模式之行为型模式的示例分析相关内容。