请说出你所熟悉的几种设计模式。并举例说明:
下面列举四种最常用的设计模式
一、Strategy模式
1、两大原则
Strategy模式体现了如下的两大原则:
1,针对接口编程,而不是针对实现编程。
2,多用组合,少用继承。
2、 例子:
二、Iterator模式
提供一种方法顺序访问一个聚合对象中各个元素, 而又不需暴露该对象的内部表示。
这种设计模式非常普遍,
比如Java里面的:
public interface Iterator {
boolean hasNext();
Object next();
void remove();
}
以及C++ STL里面的 iterator使用 ++ 访问。
三、Singleton模式
下面是个C++ singleton的类:
- 1 #ifndef SINGLETON_H
- 2 #define SINGLETON_H
- 3
- 4 #include "synobj.h"
- 5
- 6 template<class T>
- 7 class Singleton {
- 8 CLASS_UNCOPYABLE(Singleton)
- 9 public:
- 10 static T& Instance() { // Unique point of access
- 11 if (0 == _instance) {
- 12 Lock lock(_mutex);
- 13 if (0 == _instance) {
- 14 _instance = new T();
- 15 atexit(Destroy);
- 16 }
- 17 }
- 18 return *_instance;
- 19 }
- 20 protected:
- 21 Singleton(){}
- 22 ~Singleton(){}
- 23 private:
- 24 static void Destroy() { // Destroy the only instance
- 25 if ( _instance != 0 ) {
- 26 delete _instance;
- 27 _instance = 0;
- 28 }
- 29 }
- 30 static Mutex _mutex;
- 31 static T * volatile _instance; // The one and only instance
- 32 };
- 33
- 34 template<class T>
- 35 Mutex Singleton<T>::_mutex;
- 36
- 37 template<class T>
- 38 T * volatile Singleton<T>::_instance = 0;
- 39
- 40 #endif/*SINGLETON_H*/
四、Factory Method模式
Factory Method模式在不同的子工厂类生成具有统一界面接口的对象,一方面,可以不用关心产品对象的具体实现,简化和统一Client调用过程;另一方面,可以让整个系统具有灵活的可扩展性。
- abstract class BallFactory{
- protected abstract Ball makeBall(); //Factory Method
- }
- class BasketballFact extends BallFactory{
- public Ball makeBall(){ //子类实现Factory Method决定实例化哪一个类的
- return new Basketball();
- }
- }
- class FootballFact extends BallFactory{
- public Ball makeBall(){ //子类实现Factory Method决定实例化哪一个类的
- return new Football();
- }
- }
- class Basketball extends Ball{
- public void play(){
- System.out.println("play the basketball");
- }
- }
- class Football extends Ball{
- public void play(){
- System.out.println("play the football");
- }
- }
- abstract class Ball{
- protected abstract void play();
- }
- public class test{
- public static void main(String[] args){
- BallFactory ballFactory=new BasketballFact();
- Ball basketball=ballFactory.makeBall();
- basketball.play();
- ballFactory=new FootballFact();
- Ball football=ballFactory.makeBall();
- football.play();
- }
- }