[关闭]
@ranger-01 2018-05-14T18:06:32.000000Z 字数 4151 阅读 884

精通设计模式

精通


设计模式基础与原则

  1. 设计模式基础:
    • 抽象
    • 封装
    • 继承
    • 多态
  2. 设计模式的原则
    • 开闭原则(Open Close Principle)
      • 对扩展开放,对修改关闭。想要达到这样的效果,我们需要使用接口和抽象类
    • 里氏代换原则(Liskov Substitution Principle)
      • 任何基类可以出现的地方,子类一定可以出现
      • LSP 是继承复用的基石,只有当派生类可以替换掉基类,且软件单位的功能不受到影响时,基类才能真正被复用,而派生类也能够在基类的基础上增加新的行为。
      • 实现开闭原则的关键步骤就是抽象化,而基类与子类的继承关系就是抽象化的具体实现,所以里氏代换原则是对实现抽象化的具体步骤的规范。
    • 依赖倒转原则(Dependence Inversion Principle)
      • 针对接口编程,依赖于抽象而不依赖于具体。
    • 接口隔离原则(Interface Segregation Principle)
      • 降低类之间的耦合度
    • 迪米特法则,又称最少知道原则(Demeter Principle)
      • 一个实体应当尽量少地与其他实体之间发生相互作用,使得系统功能模块相对独立。
    • 合成复用原则(Composite Reuse Principle)
      • 尽量使用合成/聚合的方式,而不是使用继承。
  1. # mother can only read book, 依赖的具体Book
  2. class Book{
  3. public String getContent(){
  4. return "很久很久以前有一个阿拉伯的故事……";
  5. }
  6. }
  7. class Mother{
  8. public void narrate(Book book){
  9. System.out.println("妈妈开始讲故事");
  10. System.out.println(book.getContent());
  11. }
  12. }
  13. public class Client{
  14. public static void main(String[] args){
  15. Mother mother = new Mother();
  16. mother.narrate(new Book());
  17. }
  18. }
  19. # 依赖接口,方便扩展
  20. interface IReader{
  21. public String getContent();
  22. }
  23. class Newspaper implements IReader {
  24. public String getContent(){
  25. return "林书豪17+9助尼克斯击败老鹰……";
  26. }
  27. }
  28. class Book implements IReader{
  29. public String getContent(){
  30. return "很久很久以前有一个阿拉伯的故事……";
  31. }
  32. }
  33. class Mother{
  34. # 依赖IReader接口,子类(Book,Newspaper可以替换IReader)
  35. public void narrate(IReader reader){
  36. System.out.println("妈妈开始讲故事");
  37. System.out.println(reader.getContent());
  38. }
  39. }
  40. public class Client{
  41. public static void main(String[] args){
  42. Mother mother = new Mother();
  43. mother.narrate(new Book());
  44. mother.narrate(new Newspaper());
  45. }
  46. }

设计模式分类

具体例子

1. 工厂方法模式(Factory Method Pattern)

facion_method

  1. import abc
  2. class Leifeng:
  3. __metaclass__ = abc.ABCMeta
  4. @abc.abstractmethod
  5. def wash(self):
  6. """"wash"""
  7. @abc.abstractmethod
  8. def sweep(self):
  9. """sweep"""
  10. @abc.abstractmethod
  11. def buy_rice(self):
  12. """buy rice"""
  13. class Undergraduate(Leifeng):
  14. def wash(self):
  15. print "undergraduate wash"
  16. def sweep(self):
  17. print "undergraduate sweep"
  18. def buy_rice(self):
  19. print "undergraduate buy rice"
  20. class Volunteer(Leifeng):
  21. def wash(self):
  22. print "volunteer wash"
  23. def sweep(self):
  24. print "volunteer sweep"
  25. def buy_rice(self):
  26. print "volunteer buy rice"
  27. class IFactory:
  28. __metaclass__ = abc.ABCMeta
  29. @abc.abstractmethod
  30. def CreateLeifeng(self):
  31. """create class leifeng"""
  32. class UndergraduateFactory(IFactory):
  33. def CreateLeifeng(self):
  34. return Undergraduate()
  35. class VolunteerFactory(IFactory):
  36. def CreateLeifeng(self):
  37. return Volunteer()
  38. if __name__ == "__main__":
  39. # create undergraduate to sweep
  40. i_factory = UndergraduateFactory()
  41. leifeng = i_factory.CreateLeifeng()
  42. leifeng.sweep()
  43. # create volunteer to wash
  44. i_factory = VolunteerFactory() # just replace UndergraduateFactory with VolunteerFactory
  45. leifeng = i_factory.CreateLeifeng()
  46. leifeng.wash()

2. 单例模式

singleton

  1. import threading
  2. class Singleton(object):
  3. instance = None
  4. lock = threading.RLock()
  5. @classmethod
  6. def __new__(cls):
  7. if cls.instance is None:
  8. cls.lock.acquire()
  9. if cls.instance is None:
  10. cls.instance = super(Singleton, cls).__new__(cls)
  11. cls.lock.release()
  12. return cls.instance
  13. if __name__ == "__main__":
  14. instance1 = Singleton()
  15. instance2 = Singleton()
  16. print id(instance1) == id(instance2)

3. 装饰模式

decorator

  1. import abc
  2. class Person:
  3. def show(self):
  4. print "person"
  5. class Finery(Person):
  6. def __init__(self, c):
  7. self.component = c
  8. def show(self):
  9. """finery show"""
  10. class Tie(Finery):
  11. def show(self):
  12. print "tie ",
  13. self.component.show()
  14. class Suit(Finery):
  15. def show(self):
  16. print "suit ",
  17. self.component.show()
  18. class Shoes(Finery):
  19. def show(self):
  20. print "shoes ",
  21. self.component.show()
  22. if __name__ == "__main__":
  23. person = Person()
  24. tie = Tie(person)
  25. suit = Suit(tie)
  26. shoes = Shoes(suit)
  27. shoes.show()

4. 观察者模式

observer

  1. import abc
  2. class Observer:
  3. __metaclass__ = abc.ABCMeta
  4. def __init__(self, n, nr):
  5. self.name = n
  6. self.notifier = nr
  7. @abc.abstractmethod
  8. def update(self):
  9. """updated by notifier"""
  10. class NbaObserver(Observer):
  11. def update(self):
  12. print self.name + ", " + self.notifier.state + ", close NBA"
  13. class StockObserver(Observer):
  14. def update(self):
  15. print self.name + ", " + self.notifier.state + ", close stock"
  16. class Notifier:
  17. def __init__(self):
  18. self.observers = []
  19. self.state = ""
  20. def attach(self, o):
  21. self.observers.append(o)
  22. def detach(self, o):
  23. self.observers.remove(o)
  24. def notify(self):
  25. for observer in self.observers:
  26. observer.update()
  27. class Boss(Notifier):
  28. pass
  29. if __name__ == "__main__":
  30. boss = Boss()
  31. nba_observer = NbaObserver("Bob", boss)
  32. boss.attach(nba_observer)
  33. stock_observer = StockObserver("Alice", boss)
  34. boss.attach(stock_observer)
  35. boss.state = "boss's back himself"
  36. boss.notify()
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注