工厂模式:

应用特性:其实工厂模式就是创建对象模式,你想要什么就给你创建什么对象。通常接收一个要求,返回一个要求的对象。

结构特性:一个独立的各类对象的生成器。

UML:


#!/usr/bin/env python
#encoding: utf-8

class baseclass:
    def __init__(self):  
        pass
    
    def dosomething(self):
        pass
    
class newclass1(baseclass):
    def __init__(self):
        pass
    
    def dosomething(self):
        print 'dosomething1'
        
class newclass2(baseclass):
    def __init__(self):
        pass
    
    def dosomething(self):
        print 'dosomething2'
        
class newclass3(baseclass):
    def __init__(self):
        pass
    
    def dosomething(self):
        print 'dosomething3'
          

class createclass:
    def __init__(self):
        pass
    
    @staticmethod
    def get_new_class(something):
        if 'newclass1' == something:
            return newclass1()
        elif 'newclass2' == something:
            return newclass2()
        elif 'newclass3' == something:
            return newclass3()
        else:
            return None
        
        
if '__main__' == __name__:
    class1 = createclass.get_new_class('newclass1')
    class2 = createclass.get_new_class('newclass2')
    class3 = createclass.get_new_class('newclass3')
    print class1.__class__
    print class2.__class__
    print class3.__class__
        

结果:

__main__.newclass1
__main__.newclass2
__main__.newclass3


Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐