본문 바로가기
파이썬

파이썬 simple Abcstract factory pattern example

by 혜룐 2015. 11. 10.

간단한 팩토리로 구현한 코드이다.
남은 작업으로는 구상클래스부분인데, sectionType이 추가되거나 변경될때마다 코드에 수정이 가해진다.
catherineui-MacBook-Pro:~ catherine$ cat dds.log
author__ = 'catherine'
class AbstractScoreNews(object):
def articleScore(self, sectionIndex, index) :
raise NotImplementedError
class DScoreNewsFactory(object):
@staticmethod
def factory(sectionType):
if sectionType == 'newsflash': return DNewsflash()
if sectionType == 'text': return DText()
if sectionType == 'image': return DImage()
class DNewsflash(AbstractScoreNews):
def articleScore(self, sectionIndex, index) :
#bla..
return 1.4
class DText(AbstractScoreNews):
def articleScore(self, sectionIndex, index) :
#bla..
return 0.3
class DImage(AbstractScoreNews):
def articleScore(self, sectionIndex, index) :
#bla..
return 0.4
Test코드에서는
__author__ = 'catherine'
class TestKrawler(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.urlTask = UrlTask("http://www.m.m.com")
cls.urlTask.parser_type = 'P'
#bla..
def test_AbstractScoreNews_factory(self):
r1 = DScoreNewsFactory.factory('newsflash').articleScore('0','0')
r2 = DScoreNewsFactory.factory('text').articleScore('0','0')
r3 = DScoreNewsFactory.factory('image').articleScore('0','0')
print 'Result : ', r1 , r2, r3
raise는 일부러 에러를 발생시키기 위해서 사용하는 명령어로 경우에 따라서 어떠한 프로그래밍을 강제하기 위해서 사용할 수 있다. 예를 들어 클래스를 만들고 이를 상속받는 클래스에서 메소드를 반드시 구현하게 만들기 위해서는 아래와 같이 부모 클래스에서 raise를 이용할 수 있다.
참고주소
http://python-3-patterns-idioms-test.readthedocs.org/en/latest/Factory.html
http://egloos.zum.com/minamjun11/v/14560
http://www.linuxtopia.org/online_books/programming_books/python_programming/python_ch23.html