设计模式面试——四种最常用的设计模式

来源:互联网 发布:交换机端口流量不稳定 编辑:程序博客网 时间:2024/06/07 18:11

请说出你所熟悉的几种设计模式。并举例说明:

下面列举四种最常用的设计模式


一、Strategy模式

1、两大原则
Strategy模式体现了如下的两大原则:

1,针对接口编程,而不是针对实现编程。

2,多用组合,少用继承。
2、 例子:


二、Iterator模式

提供一种方法顺序访问一个聚合对象中各个元素, 而又不需暴露该对象的内部表示。
这种设计模式非常普遍,
比如Java里面的:
public interface Iterator {
boolean hasNext();
Object next();
void remove();
}
以及C++ STL里面的 iterator使用 ++ 访问。

三、Singleton模式
下面是个C++ singleton的类:

[cpp] view plaincopy
  1. 1 #ifndef SINGLETON_H  
  2. 2 #define SINGLETON_H  
  3. 3  
  4. 4 #include "synobj.h"  
  5. 5  
  6. template<class T>  
  7. class Singleton {  
  8. 8   CLASS_UNCOPYABLE(Singleton)  
  9. public:  
  10. 10   static T& Instance() { // Unique point of access  
  11. 11   if (0 == _instance) {  
  12. 12     Lock lock(_mutex);  
  13. 13     if (0 == _instance) {  
  14. 14     _instance = new T();  
  15. 15     atexit(Destroy);  
  16. 16     }  
  17. 17   }  
  18. 18   return *_instance;  
  19. 19   }  
  20. 20 protected:  
  21. 21   Singleton(){}  
  22. 22   ~Singleton(){}  
  23. 23 private:  
  24. 24   static void Destroy() { // Destroy the only instance  
  25. 25   if ( _instance != 0 ) {  
  26. 26     delete _instance;  
  27. 27     _instance = 0;  
  28. 28   }  
  29. 29   }  
  30. 30   static Mutex _mutex;  
  31. 31   static T * volatile _instance; // The one and only instance  
  32. 32 };  
  33. 33  
  34. 34 template<class T>  
  35. 35 Mutex Singleton<T>::_mutex;  
  36. 36  
  37. 37 template<class T>  
  38. 38 T * volatile Singleton<T>::_instance = 0;  
  39. 39  
  40. 40 #endif/*SINGLETON_H*/   


四、Factory Method模式
Factory Method模式在不同的子工厂类生成具有统一界面接口的对象,一方面,可以不用关心产品对象的具体实现,简化和统一Client调用过程;另一方面,可以让整个系统具有灵活的可扩展性。


[cpp] view plaincopy
  1. abstract class BallFactory{  
  2. protected abstract Ball makeBall(); //Factory Method  
  3. }  
  4. class BasketballFact extends BallFactory{  
  5. public Ball makeBall(){    //子类实现Factory Method决定实例化哪一个类的  
  6.  return new Basketball();  
  7. }  
  8. }  
  9. class FootballFact extends BallFactory{  
  10. public Ball makeBall(){   //子类实现Factory Method决定实例化哪一个类的  
  11.  return new Football();  
  12. }  
  13. }  
  14. class Basketball extends Ball{  
  15. public void play(){  
  16.  System.out.println("play the basketball");  
  17. }  
  18. }  
  19. class Football extends Ball{  
  20. public void play(){  
  21.  System.out.println("play the football");  
  22. }  
  23. }  
  24. abstract class Ball{  
  25. protected abstract void play();  
  26. }  
  27. public class test{  
  28. public static void main(String[] args){  
  29.  BallFactory ballFactory=new BasketballFact();  
  30.  Ball basketball=ballFactory.makeBall();  
  31.  basketball.play();  
  32.    
  33.  ballFactory=new FootballFact();  
  34.  Ball football=ballFactory.makeBall();  
  35.  football.play();  
  36. }  
  37. }  
原创粉丝点击