Advertisement
csaki

Adapter pattern example

Mar 6th, 2014
163
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.88 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5.  
  6. namespace AdapterExample
  7. {
  8.     // We try to adapt a robot to be a human!
  9.     // We need an adaptor class for this. Example below...
  10.  
  11.     abstract class Human
  12.     {
  13.         public abstract string GetName();
  14.         public abstract int GetIQ();
  15.     }
  16.  
  17.     abstract class Robot
  18.     {
  19.         public abstract string GetName();
  20.         public abstract int GetMemory();
  21.     }
  22.  
  23.     class Student : Human
  24.     {
  25.         string name;
  26.         int IQ;
  27.         public override string GetName()
  28.         {
  29.             return name;
  30.         }
  31.         public override int GetIQ()
  32.         {
  33.             return IQ;
  34.         }
  35.  
  36.         public Student(string name, int IQ)
  37.         {
  38.             this.name = name;
  39.             this.IQ = IQ;
  40.         }
  41.     }
  42.  
  43.     class Robot2Human : Human
  44.     {
  45.         Robot robot;
  46.         public Robot2Human(Robot r)
  47.         {
  48.             robot = r;
  49.         }
  50.         public override string GetName()
  51.         {
  52.             return robot.GetName();
  53.         }
  54.         public override int GetIQ()
  55.         {
  56.             return robot.GetMemory();
  57.         }
  58.     }
  59.  
  60.     class StarWarsRobot : Robot
  61.     {
  62.         string name;
  63.         int memory;
  64.         public override string GetName()
  65.         {
  66.             return name;
  67.         }
  68.         public override int GetMemory()
  69.         {
  70.             return memory;
  71.         }
  72.  
  73.         public StarWarsRobot(string name, int memory)
  74.         {
  75.             this.name = name;
  76.             this.memory = memory;
  77.         }
  78.     }
  79.  
  80.     class Program
  81.     {
  82.         static void Main(string[] args)
  83.         {
  84.             Robot r2d2 = new StarWarsRobot("R2D2", 1024);
  85.             Human human = new Robot2Human(r2d2);
  86.             Console.WriteLine(human.GetIQ()); // 1024
  87.             Console.ReadLine();
  88.         }
  89.     }
  90. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement