所需知识
- C++基础知识多态
- UML类图基本元素
- UML类图关系组合
注意
设计模式不是针对语言的,而是针对OO编程的(所以不管你是学Java还是C++或者其他面向OOP语言),设计模式是在总结中得到的。不是发明设计模式,而是发现。
重点
(1) 多用组合,少用继承。
(2) 针对接口编程,而不是针对实现编程。
(3) 策略模式:定义算法族,分别封装起来,让他们之间可以互相替换,此模式让算法的变化独立于使用算法的客户。
说明
Java有接口说法,而在C++中则没有。一般说接口,那就是指示一个C++抽象类。
模型
C++示例代码
// strategy.h
#pragma once
class Strategy
{
public:
Strategy() { }
virtual ~Strategy();
virtual void AlgorithmInterface() = 0;
};
class ConcreteStrategyA : public Strategy
{
public:
ConcreteStrategyA() { }
virtual ~ConcreteStrategyA();
void AlgorithmInterface();
};
class ConcreteStrategyB : public Strategy
{
public:
ConcreteStrategyB() { }
virtual ~ConcreteStrategyB();
void AlgorithmInterface();
};
// strategy.cpp
#include "strategy.h"
#include <iostream>
Strategy::~Strategy()
{
std::cout << "~Strategy()" << std::endl;
}
ConcreteStrategyA::~ConcreteStrategyA()
{
std::cout << "~ConcreteStrategy()" << std::endl;
}
void ConcreteStrategyA::AlgorithmInterface()
{
std::cout << "ConcreteStrategyA "
"AlgorithmInterface()" << std::endl;
}
ConcreteStrategyB::~ConcreteStrategyB()
{
std::cout << "~ConcreteStrategy()" << std::endl;
}
void ConcreteStrategyB::AlgorithmInterface()
{
std::cout << "ConcreteStrategyB "
"AlgorithmInterface()" << std::endl;
}
// context.h
#pragma once
class Strategy;
class Context
{
public:
Context(Strategy *stg);
~Context();
void doAction();
private:
Strategy *stg_;
};
// context.cpp
#include "context.h"
#include "strategy.h"
Context::Context(Strategy *stg)
: stg_(stg)
{ }
Context::~Context()
{
if(!stg_)
delete stg_;
}
void Context::doAction()
{
stg_->AlgorithmInterface();
}
例子
接下来看《Head First设计模式》中策略模式之鸭子。
UML类图
代码实现
#include <iostream>
class FlyBehavior
{
public:
virtual void fly() = 0;
};
class FlyWithWings : public FlyBehavior
{
public:
void fly()
{
std::cout << "I'm flying!" << std::endl;
}
};
class FlyNoWay : public FlyBehavior
{
public:
void fly()
{
std::cout << "I cann't fly!" << std::endl;
}
};
class QuackBehavior
{
public:
virtual void quack() = 0;
};
class Quack : public QuackBehavior
{
public:
void quack()
{
std::cout << "Quack ..." << std::endl;
}
};
class Squeak : public QuackBehavior
{
public:
void quack()
{
std::cout << "Squeak ..." << std::endl;
}
};
class MuteQuack : public QuackBehavior
{
public:
void quack()
{
std::cout << "Mutequack ..." << std::endl;
}
};
class Duck
{
protected:
FlyBehavior *flyBehavior;
QuackBehavior *quackBehavior;
virtual ~Duck()
{
delete flyBehavior;
delete quackBehavior;
}
public:
void performQuack()
{
quackBehavior->quack();
}
void performFly()
{
flyBehavior->fly();
}
void setFlyBehavior(FlyBehavior *f)
{
flyBehavior = f;
}
void setQuackBehavior(QuackBehavior *q)
{
quackBehavior = q;
}
};
class MallardDuck : public Duck
{
public:
MallardDuck() : Duck()
{
flyBehavior = new FlyWithWings;
quackBehavior = new Quack;
}
void dispaly()
{
std::cout << "I'm a real mallard duck!" << std::endl;
}
};
引用
《Head Fist设计模式》,美Freeman ,中国电力出版社,2007/09/01
设计模式精解-GoF 23 种设计模式解析附 C++实现源码