一个Adapter模式的小例子
2010-04-10 13:40
330 查看
画圆和长方形的方法是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();
}
}
//目标接口:
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();
}
}
相关文章推荐
- 一个例子讲解adapter设计模式(非常简单)
- 用一个例子解释Adapter设计模式
- Adapter设计模式的一个例子,HandlerAdapter
- 用一个例子讲解Adapter设计模式
- C# 关于委托和事件的妙文:通过一个例子详细介绍委托和事件的作用;Observer模式简介
- 用装饰模式优化代码的一个简单例子
- 一个简单的观察者模式例子
- 根据java的设计原则、设计模式实现了一个信息发送和接收的例子
- 用装饰模式优化代码的一个简单例子
- 一个单例模式的简单例子
- Android设计模式之一个例子让你彻底明白工厂模式(Factory Pattern)
- 基于人吃饭的例子设计一个装饰设计模式:
- 一个Bridge模式的例子
- JAVA的单例模式(用java写一个singleton的例子)。
- 一个用观察者模式解决实际问题的例子
- Observer模式 的一个简单的例子
- 一个简单工厂模式的小例子
- 应用开发的结构浅析----一个基于Proxy-Stub模式的例子
- 用装饰模式优化代码的一个简单例子
- 一个例子-页面列表模式、缩略图模式切换