适配器模式
将一个类的接口转换成客户希望的另一个接口。
Adapter模式使原来由于接口不兼容而不能一起工作的那些类能够一起工作。
GOF设计模式
Adapter模式主要应用于“希望复用一些现存的类,但是接口又与复
用环境要求不一致的情况“,在遗留代码复用,类库迁移等方面非常有用。
Adapter模式使原来由于接口不兼容而不能一起工作的那些类能够一起工作。
GOF设计模式
Adapter模式主要应用于“希望复用一些现存的类,但是接口又与复
用环境要求不一致的情况“,在遗留代码复用,类库迁移等方面非常有用。
using System.Collections;
using System;
interface IStack //客户期望的接口
{
void Push(Object item);
Object Pop();
Object Peek();
}
using System;
interface IStack //客户期望的接口
{
void Push(Object item);
Object Pop();
Object Peek();
}
//对象适配器
class Adapter : IStack //适配对象
{
ArrayList adpatee;//被适配的对象1
//可以适配多个
ArrayList adpatee2;//被适配的对象2
public Adapter()
{
adpatee = new ArrayList();
}
public void Push(Object item)
{
adpatee.Add(item);
}
Object Pop()
{
adpatee.RemoveAt(adpatee.Count - 1);
}
Object Peek()
{
return adpatee(adpatee.Count - 1);
}
}
class Adapter : IStack //适配对象
{
ArrayList adpatee;//被适配的对象1
//可以适配多个
ArrayList adpatee2;//被适配的对象2
public Adapter()
{
adpatee = new ArrayList();
}
public void Push(Object item)
{
adpatee.Add(item);
}
Object Pop()
{
adpatee.RemoveAt(adpatee.Count - 1);
}
Object Peek()
{
return adpatee(adpatee.Count - 1);
}
}
//类适配器(违反了类应该具有单一职责的原则)
class Adapter : ArrayList,IStack
{
public void Push(Object item)
{
this.Add(item);
}
Object Pop()
{
return this.RemoveAt(list.Count - 1);
}
Object Peek()
{
return this(this.Count - 1);
}
}
class Adapter : ArrayList,IStack
{
public void Push(Object item)
{
this.Add(item);
}
Object Pop()
{
return this.RemoveAt(list.Count - 1);
}
Object Peek()
{
return this(this.Count - 1);
}
}
集合类中对现有对象的非序
现有对象未实现IComparable接口
实现一个排序适配器(继随IComparer接口),然后在
其Compare方法中对两个对象进行比较
class Employee
{
int age;
string name;
public int Age
{
get{return this.age;}
set{this.age = value;}
}
}
class EmployeeSortAdapter : IComparer
{
public int Compare(Object obj1, Object obj2)
//不一定按适配器模式来,把适配对象作为参数传递同样,例如此处的Object
{
if(obj1.GetType() != typeOf(Employee) || obj2.GetType() != typeOf(Employee))
{
//throw a Exception
}
Employee e1 = (Employee)obj1;
Employee e2 = (Employee)obj2;
if(e1.Age == e2.Age)
{
return 0 ;
}
if(e1.Age > e2.Age)
{
return 1;
}
if(e1.Age < e2.Age)
{
return -1;
}
}
}
class App
{
public static void Mian()
{
Employeep[] employee = new Employee[100];
//.赋值
//排序
Array.Sort(employee, new EmployeeSortAdapter());
}
}
现有对象未实现IComparable接口
实现一个排序适配器(继随IComparer接口),然后在
其Compare方法中对两个对象进行比较
class Employee
{
int age;
string name;
public int Age
{
get{return this.age;}
set{this.age = value;}
}
}
class EmployeeSortAdapter : IComparer
{
public int Compare(Object obj1, Object obj2)
//不一定按适配器模式来,把适配对象作为参数传递同样,例如此处的Object
{
if(obj1.GetType() != typeOf(Employee) || obj2.GetType() != typeOf(Employee))
{
//throw a Exception
}
Employee e1 = (Employee)obj1;
Employee e2 = (Employee)obj2;
if(e1.Age == e2.Age)
{
return 0 ;
}
if(e1.Age > e2.Age)
{
return 1;
}
if(e1.Age < e2.Age)
{
return -1;
}
}
}
class App
{
public static void Mian()
{
Employeep[] employee = new Employee[100];
//.赋值
//排序
Array.Sort(employee, new EmployeeSortAdapter());
}
}