namespace _06_Adapter
{
interface IStack //客户期望的接口
{
void Push(object item);
object Pop();
object Peek();
}
/// <summary>
/// 对象适配器
/// </summary>
class AdapterObject : IStack //适配对象, 对象适配器
{
ArrayList Adaptee; //被适配的对象
public AdapterObject()
{
Adaptee = new ArrayList();
}
public void Push(object item)
{
Adaptee.Add(item);
}
public object Pop()
{
object obj = Adaptee[Adaptee.Count - 1];
Adaptee.RemoveAt(Adaptee.Count - 1);
return obj;
}
public object Peek()
{
return Adaptee[Adaptee.Count - 1];
}
}
/// <summary>
/// 类适配器
/// </summary>
class AdapterClass : ArrayList, IStack //ArrayList和IStack有公共接口
{
public void Push(object item)
{
this.Add(item);
}
public object Pop()
{
object obj = this[this.Count - 1];
this.RemoveAt(this.Count - 1);
return obj;
}
public object Peek()
{
return this[this.Count - 1];
}
}
/// <summary>
/// 现有类
/// </summary>
class ExistingClass
{
public void SpecificRequest1()
{
}
public void SpecificRequest2()
{
}
}
/// <summary>
/// 新环境所使用的接口
/// </summary>
interface ITarget
{
void Request();
}
/// <summary>
/// 另外一个系统
/// </summary>
class MySystem
{
public void Process(ITarget target)
{
target.Request();
}
}
class Adapter : ITarget
{
ExistingClass adaptee;
public Adapter()
{
adaptee = new ExistingClass();
}
public void Request()
{
adaptee.SpecificRequest1();
adaptee.SpecificRequest2();
}
}
public class Employee
{
private int age = 0;
private string name;
public int Age
{
get { return age; }
set { age = value; }
}
}
class EmployeeSortAdapter : IComparer
{
//object obj1;
//object obj2;
//public EmployeeSortAdapter(object obj1, object obj2)
//{
// this.obj1 = obj1;
// this.obj2 = obj2;
//}
public int Compare(object obj1, object obj2)
{
if (obj1.GetType() != typeof(Employee) || obj2.GetType() != typeof(Employee))
{
throw new ArgumentException();
}
Employee e1 = (Employee)obj1;
Employee e2 = (Employee)obj2;
if (e1.Age == e2.Age)
{
return 0;
}
else if (e1.Age > e2.Age)
{
return 1;
}
else if (e1.Age < e2.Age)
{
return -1;
}
else
{
throw new Exception();
return -99;
}
}
}
internal class Program
{
static void Main(string[] args)
{
//MySystem ms = new MySystem();
//ms.Process(new Adapter());
Employee[] employees = new Employee[100];
int num = 1000;
for (int i = 0; i < 100; i++)
{
employees[i] = new Employee();
employees[i].Age = num;
num -= 1;
}
Array.Sort(employees, new EmployeeSortAdapter());
Console.ReadKey();
}
}
}
02-27
02-18
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交