设计模式笔录(一)

来源:互联网 发布:sql取绝对值 编辑:程序博客网 时间:2024/05/18 03:24

<<类适配器>>
class Shape
{
public:
virtual void BoundingBox(Point& bottomLeft, Point& topRight) const;
virtual Manipulator* CreateManipulator() const;//是一个Factory Method 的实例
};
class TextView
{
public:
TextView();
void GetOrigin(Coord& x, Coord& y) const;
void GetExtent(coord& width, Coord& height) const;
virtual bool IsEmpty() const;
};
class TextShape : public Shape, private TextView //此处继承模式是关键。
{
public:
TextShape();
virtual void BoundingBox(Point& bottomLeft, Point& topRight) const
{
Coord bottom, top, width, height;
GetOrigin(bottom,left);
GetExtent(width,height);
bottomLeft = Point(bottom,left);
topRight   = Point(bottom + height, top + width);
}
bool IsEmpty() const
{
return TextView::IsEmpty();
}
Manipulator* CreateManipulator() const 
{
return new TextManipulator();
}
}
<<对象适配器>>
class TextShape: public Shape
{
public:
TextShape(TextView* t)
{
_text = t;
}
virtual void BoundingBox(Point& bottomLeft, Point& topRight) const
{
Coord bottom, top, width, height;
_text->GetOrigin(bottom,left);
_text->GetExtent(width,height);
bottomLeft = Point(bottom,left);
topRight   = Point(bottom + height, top + width);
}
bool IsEmpty() const
{
return _text->IsEmpty();
}
Manipulator* CreateManipulator() const 
{
return new TextManipulator();
}
private:
TextView* _text;
}


<<组合模式>>
class Graphic : Line, Rectangle, Text, Picture//部分-整体模型


<<装饰模式>>
一种较为灵活的方式是将组件嵌入到另一个对象中,由这个对象添加边框,我们称这个嵌入的对象为装饰。
 这个装饰和它所装饰的组件接口一致,因此它对使用该组件的客户透明。
class VirtualComponent
{
public:
VirtualComponent();
virtual void Draw();
virtual void Resize();
//...
}
class Decorator : public VirtualComponent
{
public:
Decorator(VirtualCompont*);
virtual void Draw()
{
_component->Draw();
}
virtual void Resize()
{
_component->Resize();
}
//...
private:
VirtualComponet* _compnent;
}
现在我们可以创建一个正文视图以及放入这个正文视图的窗口:


Window* window = new Window();
TextView* textView = new TextView();

TextView是一个VisualComponent,它可以放入窗口中:


window->SetContents(textView);

但我们想要一个有边界的和可以滚动的TextView,因此我们在将它放入窗口之前对其进行装饰:


window->SetContents( new BorderDecorator(new ScrollDecorator(textView),1));




<<>>