放假啦~学生们要买车票回家了,有汽车票、火车票,等。但是,车站很远,又要考试,怎么办呢?找代理买啊,虽然要多花点钱,但是,说不定在搞活动,有折扣呢~

设计模式学习——代理模式(Proxy Pattern)-LMLPHP

  ///
/// @file Selling_Tickets.h
/// @author marrs(chenchengxi993@gmail.com)
/// @date 2017-08-13 20:35:28
/// #ifndef __SELLING_TICKETS_H__
#define __SELLING_TICKETS_H__ #include <iostream> namespace marrs{ using std::cout;
using std::endl; class SellingTickets
{
public:
virtual ~SellingTickets(){} public:
virtual void Selling() = ;
virtual void Price() = ; }; } #endif // __SELLING_TICKETS_H__
  ///
/// @file Tickets.h
/// @author marrs(chenchengxi993@gmail.com)
/// @date 2017-08-13 20:39:17
/// #ifndef __TICKETS_H__
#define __TICKETS_H__ #include "Selling_Tickets.h" namespace marrs{ class Tickets
: public SellingTickets
{ }; } #endif // __TICKETS_H__
  ///
/// @file Bus_Ticket.h
/// @author marrs(chenchengxi993@gmail.com)
/// @date 2017-08-13 20:41:08
/// #ifndef __BUS_TICKET_H__
#define __BUS_TICKET_H__ #include "Tickets.h" namespace marrs{ class BusTicket
: public Tickets
{
public:
void Selling()
{
cout << "selling : BusTicket" << endl;
} void Price()
{
cout << "price : 80 RMB" << endl;
}
}; } #endif // __BUS_TICKET_H__
  ///
/// @file Train_Ticket.h
/// @author marrs(chenchengxi993@gmail.com)
/// @date 2017-08-13 20:41:08
/// #ifndef __TRAIN_TICKET_H__
#define __TRAIN_TICKET_H__ #include "Tickets.h" namespace marrs{ class TrainTicket
: public Tickets
{
public:
void Selling()
{
cout << "selling : TrainTicket" << endl;
} void Price()
{
cout << "price : 100 RMB" << endl;
}
}; } #endif // __TRAIN_TICKET_H__
  ///
/// @file Proxy.h
/// @author marrs(chenchengxi993@gmail.com)
/// @date 2017-08-13 20:46:13
/// #ifndef __PROXY_H__
#define __PROXY_H__ #include "Tickets.h" namespace marrs{ class Proxy
: public SellingTickets
{
public:
Proxy(Tickets * ticket)
: _ticket(ticket)
{
} ~Proxy()
{
delete _ticket;
} public:
void Selling()
{
_ticket->Selling();
} void Price()
{
_ticket->Price();
Proxy_Price();
Discount();
} private:
void Proxy_Price()
{
cout << "proxy price : 50 RMB" << endl;
} void Discount()
{
cout << "discount : 50%" << endl;
} private:
Tickets * _ticket; }; } #endif // __PROXY_H__
  ///
/// @file Student.cc
/// @author marrs(chenchengxi993@gmail.com)
/// @date 2017-08-13 20:51:42
/// #include "Proxy.h"
#include "Bus_Ticket.h"
#include "Train_Ticket.h" using namespace marrs; int main()
{
Proxy * proxy;
proxy = new Proxy(new BusTicket);
proxy->Selling();
proxy->Price();
delete proxy; proxy = new Proxy(new TrainTicket);
proxy->Selling();
proxy->Price();
delete proxy; return ;
}

编译,运行

[ccx@ubuntu ~/object-oriented/Proxy_Pattern]$>g++ * -o Tickets.exe
[ccx@ubuntu ~/object-oriented/Proxy_Pattern]$>./Tickets.exe
selling : BusTicket
price : RMB
proxy price : RMB
discount : %
selling : TrainTicket
price : RMB
proxy price : RMB
discount : %
04-08 13:35