zoukankan      html  css  js  c++  java
  • 设计模式之适配器模式

        适配器模式主要用于当我们写的代码与旧代码(可能不是我们写的)无法兼容时,做类型兼容,这样我们就可以轻松使用旧代码中的功能了,这个模式和装饰模式很像。

    但二者还是有所区别的,装饰模式主要是为了为类添加装饰功能,将核心功能与装饰功能分开。适配器模式主要是为了新旧代码的兼容万不得已才使用

    代码如下:

    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();
    
            }
        }
    }

    运行结果:

  • 相关阅读:
    【转】Linux目录结构FHS
    单链表是否有环并如何找到环入口
    【转】linux dd 的简单应用
    DataSet、ExecuteScalar、ExecuteReader
    解决Excel只验证前8行字符串的长度
    SQL Server UPSERT equivalent
    用通配符替换字符串
    从内存中查询表字段定义的长度大小
    C#判断一个字符串是否为整数
    page life cycle of master page with content page
  • 原文地址:https://www.cnblogs.com/JsonZhangAA/p/5559587.html
Copyright © 2011-2022 走看看