Шаблон проектирование Декоратор(Decorator || Wraper)

Август 5th, 2011 § 1 comment

Сегодня мы разберем шаблон проектирования Декоратор по другому его еще называю Врапер. Этот паттерн относится к группе структурных применяется для расширения функциональность и является гибкой альтернативой порожадению подклассов. Ниже привожу исходник на C++/C#

#include<iostream>
#include<string>
#include<list>

using namespace std;

// The 'Component' abstract class
class LibraryItem
{
public:
  void SetNumCopies(int value)
  {
    numCopies_ = value;
  }
  int GetNumCopies(void)
  {
    return numCopies_;
  }
  virtual void Display(void)=0;
private:
  int numCopies_;
};

// The 'ConcreteComponent' class#1
class Book : public LibraryItem
{
public:
  Book(string author, string title, int numCopies) : author_(author), title_(title)
  {
    SetNumCopies(numCopies);
  }
  void Display(void)
  {
    cout<<"\nBook ------ "<<endl;
    cout<<" Author : "<<author_<<endl;
    cout<<" Title : "<<title_<<endl;
    cout<<" # Copies : "<<GetNumCopies()<<endl;
  }
private:
  Book(); //Default not allowed
  string author_;
  string title_;
};

// The 'ConcreteComponent' class#2
class Video : public LibraryItem
{
public:
  Video(string director, string title, int playTime, int numCopies) : director_(director), title_(title), playTime_(playTime)
  {
    SetNumCopies(numCopies);
  }
  void Display(void)
  {
    cout<<"\nVideo ------ "<<endl;
    cout<<" Director : "<<director_<<endl;
    cout<<" Title : "<<title_<<endl;
    cout<<" Play Time : "<<playTime_<<" mins"<<endl;
    cout<<" # Copies : "<<GetNumCopies()<<endl;
  }
private:
  Video(); //Default not allowed
  string director_;
  string title_;
  int playTime_;
};

// The 'Decorator' abstract class
class Decorator : public LibraryItem
{
public:
  Decorator(LibraryItem* libraryItem) : libraryItem_(libraryItem) {}
  void Display(void)
  {
    libraryItem_->Display();
  }
  int GetNumCopies(void)
  {
    return libraryItem_->GetNumCopies();
  }
protected:
  LibraryItem* libraryItem_;
private:
  Decorator(); //not allowed
};

// The 'ConcreteDecorator' class
class Borrowable : public Decorator
{
public:
  Borrowable(LibraryItem* libraryItem) : Decorator(libraryItem) {}
  void BorrowItem(string name)
  {
    borrowers_.push_back(name);
  }
  void ReturnItem(string name)
  {
    list<string>::iterator it = borrowers_.begin();
    while(it != borrowers_.end())
    {
      if(*it == name)
      {
        borrowers_.erase(it);
        break;
      }
      ++it;
    }
  }
  void Display()
  {
    Decorator::Display();
    int size = (int)borrowers_.size();
    cout<<" # Available Copies : "<<(Decorator::GetNumCopies() - size)<<endl;
    list<string>::iterator it = borrowers_.begin();
    while(it != borrowers_.end())
    {
      cout<<" borrower: "<<*it<<endl;
      ++it;
    }
  }
protected:
  list<string> borrowers_;
};

//The Main method
int main()
{
  Book book("Erik Dahlman","3G evolution",6);
  book.Display();

  Video video("Peter Jackson", "The Lord of the Rings", 683, 24);
  video.Display();

  cout<<"Making video borrowable"<<endl;
  Borrowable borrowvideo(&video);
  borrowvideo.BorrowItem("Bill Gates");
  borrowvideo.BorrowItem("Steve Jobs");
  borrowvideo.Display();

 return 0;
}

Исходник на C#


abstract class Component
 {
 public abstract void Operation();
 }

class ConcreteComponent:Component
 {
 public override void Operation()
 {
 Console.WriteLine("This Concrete Component.Operation()");
 }
 }

protected Component component;
 public void SetComponent(Component component)
 {
 this.component = component;
 }
 public override void Operation()
 {
 if (this.component != null)
 component.Operation();
 }

 }

private string AddName;
 public override void Operation()
 {
 base.Operation();
 AddName = "New name!!!";
 Console.WriteLine("DecoratorA.Operation() + " + this.AddName);
 }
 }

public override void Operation()
 {
 base.Operation();
 Console.WriteLine("This DecoratorB.Operation() " + this.MethodB());
 }
 private string MethodB()
 {
 return "Additional functionality from method";
 }
 }

class Program
 {
 static void Main(string[] args)
 {
 ConcreteComponent comp = new ConcreteComponent();
 DecoratorA decA = new DecoratorA();
 DecoratorB decB = new DecoratorB();
 decA.SetComponent(decB);
 decB.SetComponent(comp);

 Console.WriteLine("This is DecoratorA operation: ");
 decA.Operation();
 Console.WriteLine("This is DecoratorB operation: ");
 decB.Operation();
 Console.ReadLine();
 }
 }

§ One Response to Шаблон проектирование Декоратор(Decorator || Wraper)

Ответить на immiz Отмена ответа

Ваш email не будет опубликован. Обязательные поля отмечены *

Вы можете использовать это HTMLтеги и атрибуты: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Смотреть фильмы онлайн