大胖的部落格

Just a note

  C++博客 :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理 ::
  112 随笔 :: 0 文章 :: 3 评论 :: 0 Trackbacks

Component使用户对组合对象和单一对象的操作具有一致性。
无论是组合对象还是单一对象,都从抽象基类派生;抽象基类声明所有对象共有的操作和组合对象特有的操作。
单一对象在重写针对组合对象的操作时可返回错误。
这样用户可以用同样的代码操作抽象基类类型指针,实现对组合对象和单一对象的操作,而无需关心操作对象具体类型是什么。

#include <iostream>

using namespace std;

//抽象基类
class Component
{
public:
    
//对所有Component的操作
    virtual void Display() = 0;
    
//对组合对象的操作
    virtual void Add() = 0;
}
;

//单一对象
class Element: public Component
{
public:
    
void Display() {cout<<"It's an Element"<<endl;}
    
void Add() {cout<<"Error!"<<endl;}
}
;

//组合对象
class Tree: public Component
{
public:
    
void Display() {cout<<"It's a Tree"<<endl;}
    
void Add() {++i;cout<<"Added"<<endl;}
private:
    
int i;
}
;

//用户代码,无需关注所操作的是组合对象还是单一对象
void ClientTest(Component* p)
{
    p
->Display();
    p
->Add();
}


int main()
{
    Component
* pe = new Element;
    Component
* pt = new Tree;
    ClientTest(pe);
    ClientTest(pt);
    delete pt;
    delete pe;
    
return 0;
}
posted on 2009-06-09 15:16 大胖 阅读(149) 评论(0)  编辑 收藏 引用 所属分类: Design Pattern

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理