标签:
适配器模式主要用于当我们写的代码与旧代码(可能不是我们写的)无法兼容时,做类型兼容,这样我们就可以轻松使用旧代码中的功能了,这个模式和装饰模式很像。
但二者还是有所区别的,装饰模式主要是为了为类添加装饰功能,将核心功能与装饰功能分开。适配器模式主要是为了新旧代码的兼容,万不得已才使用。
代码如下:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace 设计模式之适配器模式 { public abstract class Player { private string name; public string Name { get { return name; } set { name = value; } } abstract public void Go(); abstract public void Defend(); } public class AmericaPlayer : Player { public override void Go() { Console.WriteLine("{0} Let‘s Go!",Name); } public override void Defend() { Console.WriteLine("{0} Come back! Defend!",Name); } } public class ChinesePlayer { private string name; public string Name { get { return name; } set { name = value; } } public void 进攻() { Console.WriteLine("{0} 进攻!",name); } public void 防守() { Console.WriteLine("{0} 回来防守!",name); } } public class BetweenPlayer : Player { public ChinesePlayer cPlayer = new ChinesePlayer(); public override void Go() { cPlayer.进攻(); } public override void Defend() { cPlayer.防守(); } } class Program { static void Main(string[] args) { AmericaPlayer aPlayer = new AmericaPlayer(); aPlayer.Name = "科比"; aPlayer.Go(); aPlayer.Defend(); ChinesePlayer cPlayer = new ChinesePlayer(); cPlayer.Name = "姚明"; BetweenPlayer bPlayer = new BetweenPlayer(); bPlayer.cPlayer = cPlayer; bPlayer.Go(); bPlayer.Defend(); Console.Read(); } } }
运行结果:
标签:
原文地址:http://www.cnblogs.com/JsonZhangAA/p/5559587.html