画圆和长方形的方法是Area(),目标方法为GetArea(),所以要适配一下。
//目标接口:
interface ITarget
{
void getArea();
}
//抽象图形
public abstract class Shape
{
public abstract void Area();
}
//画圆
namespace Adapter
{
public class Circle : Shape
{
private double r;
public double R
{
get { return r; }
set { r = value; }
}
public Circle(double r)
{
this.R = r;
}
public override void Area()
{
Console.WriteLine("圆面积为{0}", 3.14 * R * R);
}
}
}
//画长方形
public class Rectangle : Shape
{
private double a, b;
public double B
{
get { return b; }
set { b = value; }
}
public double A
{
get { return a; }
set { a = value; }
}
public Rectangle(double a,double b)
{
this.A = a;
this.B = b;
}
public override void Area()
{
Console.WriteLine("长方形面积为{0}", A*B);
}
}
//类适配器
class AdapterDevice:ITarget
{
Shape _shape;
public AdapterDevice(Shape shape)
{
this._shape = shape;
}
public void getArea()
{
_shape.Area();
}
}
//客户端
class Program
{
static void Main(string[] args)
{
ITarget adapter1 = new AdapterDevice(new Circle(2));
ITarget adapter2 = new AdapterDevice(new Rectangle(2,4));
adapter1.getArea();
adapter2.getArea();
}
}