Adapter mode-I need translation in the NBA

  Adapter mode (Adapter) definition : Convert the interface of a class into another interface that the customer wants. The Adapter pattern allows those classes that cannot work together because of interface incompatibility to work together.


Insert picture description here
  Use scenario :

  • Reuse some existing classes, but the interface is inconsistent with the reuse environment
  • When both parties are not easy to modify

  Code background: Yao Ming went to the United States to play in the NBA, but he couldn't communicate with coaches and players because he couldn't speak English. The translation acted as an adapter.

Player category:

    abstract class Player
    {
    
    
        protected string name;
        public Player(string name)
        {
    
    
            this.name = name;
        }
        public abstract void Attack();//进攻
        public abstract void Defense();//防守
    }

Forward: Communicate tactics in English, Yao Ming doesn’t know what Attack() and Defense() mean

    //前锋
    class Forwards : Player
    {
    
    
        public Forwards (string name):base(name)
        {
    
     }
        public override void Attack()
        {
    
    
            Console.WriteLine("前锋{0}进攻",name);
        }
        public override void Defense()
        {
    
    
            Console.WriteLine("前锋{0}防守",name);
        }
    }

Foreign center (Yao Ming): Use Chinese to communicate tactics and only say "offensive" and "defense"

    class ForeignCenter
    {
    
    
        private string name;
        public string Name//用属性而不是用构造方法,目的是区分其他球员类
        {
    
    
            get {
    
     return name; }
            set {
    
     name = value; }
        }
        public void 进攻()
        {
    
    
            Console.WriteLine("外籍中锋{0}进攻",name);
        }
        public void 防守()
        {
    
    
            Console.WriteLine("外籍中锋{0}防守",name);
        }
    }

Translator class: the work of the adapter

    class Translator:Player
    {
    
    
    	//声明并实例化一个内部“外籍中锋”对象,表明翻译者与外籍中锋有关联
        private ForeignCenter wjzf = new ForeignCenter();
        public Translator (string name):base(name)
        {
    
    
            wjzf.Name = name;
        }
        public override void Attack()//翻译者将Attack翻译为进攻,告诉了外籍中锋
        {
    
    
            wjzf.进攻();
        }
        public override void Defense()//翻译者将Defens翻译为防守,告诉了外籍中锋
        {
    
    
            wjzf.防守();
        }
    }

Client:

        static void Main(string[] args)
        {
    
    
            Player b = new Forwards("巴蒂尔");
            b.Attack();
            b.Defense();
            Player ym = new Translator("姚明");
            ym.Attack();
            ym.Defense();

            Console.ReadKey();
        }

Guess you like

Origin blog.csdn.net/CharmaineXia/article/details/110919162