设计模式学习(自学笔记,大神绕路,不要浪费时间)

参考文档:

  * http://www.pythontip.com/pythonPatterns/detail/builder

  * https://www.cnblogs.com/Liqiongyu/p/5916710.html

 

* abstract_factory

#!/usr/bin/env/python
# -*- coding: utf-8 -*-
# @Time    : 2018/12/10 11:28
# @Author  : ChenAdong
# @Email   : aiswell@foxmail.com


class Battle:
   def __init__(self, _hero_factory=None):
      self.hero_factory = hero_factory

   def attack_damage(self):
      print "="*20
      print self.hero_factory().name + self.hero_factory().attack_damage

   def ability_power(self):
      print "=" * 20
      print self.hero_factory().name + self.hero_factory().ability_power


class Hero:
   def __init__(self, _name=None, _attack_damage=None, _ability_power=None):
      self.attack_damage = _attack_damage
      self.ability_power = _ability_power
      self.name = _name


def hero_factory():
   hero = Hero("NeverMore", "100", "200")
   return hero


if __name__ == "__main__":
   battle = Battle(hero_factory())
   battle.attack_damage()
   battle.ability_power()

  

* adapter
#!/usr/bin/env/python
# -*- coding: utf-8 -*-
# @Time    : 2018/12/10 14:15
# @Author  : ChenAdong
# @Email   : aiswell@foxmail.com


class Hero(object):
	def __init__(self):
		pass

	@staticmethod
	def attack():
		print u"输出伤害"


class Adapter(object):
	def __init__(self, obj, adapter_method):
		self.obj = obj
		self.__dict__.update(adapter_method)

	def __getattr__(self, item):
		return getattr(self.obj, item)


hero = Hero()
hero_list = []
hero_list.append(Adapter(hero, dict(ad=hero.attack)))
print hero_list
for i in hero_list:
	i.attack()

  * 共享模式(borg)

#!/usr/bin/env/python
# -*- coding: utf-8 -*-
# @Time    : 2018/12/10 14:44
# @Author  : ChenAdong
# @Email   : aiswell@foxmail.com


class Hero:
	ability_power = "10"
	attack_damage = "10"

	def __init__(self):
		pass

	def ad(self):
		return self.attack_damage


class HeroFake(Hero):
	pass


hero_1 = Hero()
hero_2 = Hero()
hero_1.attack_damage = 100
hero_2.attack_damage = 200
print hero_1.ad()
print hero_2.ad()
print hero_1.ability_power
print hero_2.ability_power

  

C:\Python27\python.exe D:/Adong_Chen/tmp/borg.py
100
200
10
10

  * bridge(桥接模式)

#!/usr/bin/env/python
# -*- coding: utf-8 -*-
# @Time    : 2018/12/10 15:11
# @Author  : ChenAdong
# @Email   : aiswell@foxmail.com


class AD(object):
	@staticmethod
	def hero(_skill, _ad):
		name = "AD"
		ad = _ad
		hp = "300"
		skill = _skill
		return name, hp, ad, skill


class AP(object):
	@staticmethod
	def hero(_skill, _ap):
		name = "AP"
		ap = _ap
		hp = "100"
		skill = _skill
		return name, hp, ap, skill


class Hero:
	def __init__(self, hero_type, _skill, damage):
		self.hero_type = hero_type
		self._skill = _skill
		self.damage = damage

	def hero(self):
		return self.hero_type.hero(self._skill, self.damage)


if __name__ == "__main__":
	hero = (
		Hero(AD, u"normal_damage", u"100"),
		Hero(AP, u"magic_damage", u"500")
	)
	for i in hero:
		print i.hero()

 * iterator(迭代器) 

def foo():
	for i in [0, 1]:
		yield i


f = foo()
for j in range(0, 2):
	print f.next()

  

C:\Python27\python.exe D:/Adong_Chen/tmp/iterator.py
0
1

  * decorator(装饰器)

username = "123"
password = "456"


class SignIn:
	def __init__(self):
		pass

	@staticmethod
	def login(_username, _password):
		if _username == username and _password == password:
			return "login"


class Operate:
	def __init__(self, deco):
		self.deco = deco

	def operate(self, _username, _password):
		if self.deco.login(_username, _password) == "login":
			print "operating"
		else:
			print "login first"


o = Operate(SignIn)
o.operate("123", "4567")

  

C:\Python27\python.exe D:/Adong_Chen/tmp/decorator.py
login first

  

* builder(建造者模式)

 

# Director
class Director(object):
   def __init__(self):
      self.builder = None

   def construct_building(self):
      self.builder.new_building()
      self.builder.build_floor()
      self.builder.build_size()

   def get_building(self):
      return self.builder.building


# Abstract Builder
class Builder(object):
   def __init__(self):
      self.building = None

   def new_building(self):
      self.building = Building()


# Concrete Builder
class BuilderHouse(Builder):
   def build_floor(self):
      self.building.floor = "one"

   def build_size(self):
      self.building.size = "big"


# Product
class Building(object):
   def __init__(self):
      self.floor = None
      self.size = None

   def __repr__(self):
      return "floor: %s, size: %s" % (self.floor, self.size)


# Client
if __name__ == "__main__":
   director = Director()
   director.builder = BuilderHouse()
   director.construct_building()
   my_building = director.get_building()
   print my_building

  


# 使用建造者模式,调用相应功能只需要如上的4步,就能获取到相应结果,并且步骤都是固定的;
# 顺序换成:Dirctor ----> Product ----> Abstract Builder ----> Concrete Builder ----> Client 写起来舒服点;


* chain-of-responsibility 职责链模式
#!/usr/bin/env/python
# -*- coding: utf-8 -*-
# @Time    : 2018/12/11 15:11
# @Author  : ChenAdong
# @Email   : aiswell@foxmail.com


class Handler:
	def successor(self, successor):
		self.successor = successor


class ConcreteHandler1(Handler):
	def handler(self, args):
		if args in range(1, 10):
			print "in handler 1"
		else:
			self.successor.handler(args)


class ConcreteHandler2(Handler):
	def handler(self, args):
		if args in range(10, 30):
			print "in handler 2"
		else:
			self.successor.handler(args)


class Client:
	def __init__(self):
		h1 = ConcreteHandler1()
		h2 = ConcreteHandler2()

		h1.successor(h2)
		for args in [1, 10, 20, 19]:
			h1.handler(args)


if __name__ == "__main__":
	client = Client()

  

C:\Python27\python.exe D:/Adong_Chen/tmp/chain.py
in handler 1
in handler 2
in handler 2
in handler 2

  上面这个例子还有写ide会显示很多下划线的问题;可能是编码风格不对。

* command 模式
import os


class Rename(object):
	def __init__(self, old_name, new_name):
		self.old_name = old_name
		self.new_name = new_name

	def rename(self):
		self()

	def __call__(self, *args, **kwargs):
		os.rename(self.old_name, self.new_name)

	def undo(self):
		os.rename(self.new_name, self.old_name)


if __name__ == "__main__":
	rename = Rename("./tem.txt", "./tt.txt")
	rename.undo()

 实际上是把简单的命令写在了object类的__call__()方法里,self()调用该方法;


* 组合模式:把多个部件,组合返回通用的调用方法(暂时这样理解的,后面学习)

* facade(外观模式)
  下面的代码来自引用网址,在该网址不能执行,可以再IDE内执行;
   外观模式代码先相对简单,就不单独做演示了
import time

SLEEP = 0.5


# Complex Parts
class TC1:
    def run(self):
        print("###### In Test 1 ######")
        time.sleep(SLEEP)
        print("Setting up")
        time.sleep(SLEEP)
        print("Running test")
        time.sleep(SLEEP)
        print("Tearing down")
        time.sleep(SLEEP)
        print("Test Finished\n")


class TC2:
    def run(self):
        print("###### In Test 2 ######")
        time.sleep(SLEEP)
        print("Setting up")
        time.sleep(SLEEP)
        print("Running test")
        time.sleep(SLEEP)
        print("Tearing down")
        time.sleep(SLEEP)
        print("Test Finished\n")


class TC3:
    def run(self):
        print("###### In Test 3 ######")
        time.sleep(SLEEP)
        print("Setting up")
        time.sleep(SLEEP)
        print("Running test")
        time.sleep(SLEEP)
        print("Tearing down")
        time.sleep(SLEEP)
        print("Test Finished\n")


# Facade
class TestRunner:
    def __init__(self):
        self.tc1 = TC1()
        self.tc2 = TC2()
        self.tc3 = TC3()
        self.tests = [i for i in (self.tc1, self.tc2, self.tc3)]

    def runAll(self):
        [i.run() for i in self.tests]


# Client
if __name__ == '__main__':
    testrunner = TestRunner()
    testrunner.runAll()

  

C:\Python27\python.exe D:/Adong_Chen/tmp/test010.py
###### In Test 1 ######
Setting up
Running test
Tearing down
Test Finished

###### In Test 2 ######
Setting up
Running test
Tearing down
Test Finished

###### In Test 3 ######
Setting up
Running test
Tearing down
Test Finished


Process finished with exit code 0

  

* Flyweight(享元模式)

  未学习,当前用不着

 
posted @ 2018-12-10 13:46  ADChen  阅读(330)  评论(0)    收藏  举报