SlideShare a Scribd company logo
Holub on PatternsChapter 3.1 – Game of Life아꿈사http://andstudy.com안명환http://eritaka.net
John Conway’s Game of Life오직 2 가지 법칙죽어 있는 셀은 3개의 이웃이 있으면 살아난다두 개 혹은 세 개의 이웃만을 가져야만 산다
특징 – Game of LifeEmergence하위 수준에는 없는 특성이 상위 수준에서 자발적으로 출현하는 현상미시 동기의 결합으로 인한 거시 행동 형성다양한 패턴 발생
Game of Life
Static Model
Design PatternSingletonVisitorObserverCompositeFacadeMediatorPrototypeMementoFlyweight
class Java Menu SubSyst...JComponent«Property>- name- text+ setName(String) : void+ getName() : String+ setText(String) : void+ getText() : StringAbstractButtonJMenuBar«interface>notifiesActionListener+ addActionListener(ActionListener) : void+ add(JMenu) : void«call?+ actionPerformed(ActionEvent) : void+ removeActionListener(ActionListener) : void# fireActionPerformed(ActionEvent) : voidObserver1SubjectObserverJMenuItemComponent & Leaf+ JMenuItem(String)Concrete ObserverConcrete Subject*Composite{submenus}<<anonymous>>1Composite+ actionPerformed(ActionEvent) : voidConcrete SubjectJMenu+ add(JMenuItem) : void*{menus}Case Study: Menu (Java Swing)
Observer 문제구현 상속 기반의 해결안abstract class BadJMenuItem {abstract void itemSelected();}classMyMenuItemextendsBadJMenuItem {public void itemSelected() {//아이템이 선택되었을 때 수행할 것...	}}문제점
모든 메뉴 아이템이 BadJMenuItem상속
BadJMenuItem을 상속한 개체에만 통지의도객체의 상태가 변경될 때 관련 객체들에게 통지하고 싶을 경우class GoF_Observ...Subject+ Attach(Observer)Observer-observers+ Detach(Observer) : Observer+ Notify() : Observer+ Update()1..*for all o in observers {  o->Update()}ConcreteSubjectConcreteObserver- subjectState- observerState-subject+ GetState()+ Update()return observerState = subjectStatesubject->GetState()+ SetState()GoF – Observer Pattern
Observer: 멀티스레드 환경 1해결책 1의 문제class Publisher1 {ArrayList subscribers = new ArrayList();// fireEvent를 기다리다가 기아 현상 발생public synchronized void subscribe(Runnable subscriber) {subscribers.add(subscriber);}public synchronized void cancelSubscribe(Runnable subscriber) {subscribers.remove(subscriber);}private synchronized void fireEvent() {for(inti=0; i < subscribers.size(); ++i)		((Runnable)subscribers.get(i)).run(); // 시간이 걸린다!}}
Observer: 멀티스레드 환경 2해결책 2의 문제class Publisher2 {private Collection subscribers = newLinkedList();// Iterator연산 중 add, remove 호출 시 예외 발생public synchronized void subscribe(Runnable subscriber) {subscribers.add(subscriber);}public synchronized void cancelSubscribe(Runnable subscriber) {subscribers.remove(subscriber);}private void fireEvent() {for( Iteratori=subscribers.iterator(); i.hasNext(); )		((Runnable)i.next()).run(); }}
Observer: 멀티스레드 환경 3해결책 3의 문제class Publisher3 {private Collection subscribers = newLinkedList();public synchronized void subscribe(Runnable subscriber) {subscribers.add(subscriber);}public synchronized void cancelSubscribe(Runnable subscriber) {subscribers.remove(subscriber);}// 통지 이벤트 시마다 복사본이 생성 (구독취소 이벤트와 상관없이)private void fireEvent() {Collection localCopy;synchronized( this ) {localCopy = subscribers.clone();}for( Iteratori=localCopy.iterator(); i.hasNext();)	((Runnable)i.next()).run();}}
Observer: 멀티스레드 환경 4불변 객체 노드를 사용하는 리스트 해결법이전:헤드d:Objectc:Objectb:Objecta:Object이후:가비지 컬렉션 될 것임이전 헤드d:Objectc:Objectb:Objecta:Object헤드
class GoF_VisitorVisitor+ VisitConcreteElementA(ConcreteElementA)+ VisitConcreteElementB(ConcreteElementB)ConcreteVisitor1ConcreteVisitor2+ VisitConcreteElementA(ConcreteElementA)+ VisitConcreteElementA(ConcreteElementA)+ VisitConcreteElementB(ConcreteElementB)+ VisitConcreteElementB(ConcreteElementB)ElementObjectStructure1..*+ Accept(Visitor)ConcreteElementAConcreteElementB+ Accept(Visitor)+ Accept(Visitor)v->VisitConcreteElementA(this)v->VisitConcreteElementB(this)GoF– Visitor Pattern의도기존 계층 구조를 수정하지 않고 새로운 메소드를 추가하고자 할 때전문가 도입
sd LifeGameVisitorClockpublishersubscribers[i] ::Distributorsubscribers[i].subscriberNodetick()publish(:Distributor)*accept(:Distributor)deliverTo(subscribers[i].subscriber)tick()"visit" 메소드sd GoF_VisitoraObjectStructureaConcreteElement[i]aConcreteVisitor*accept(Distributor)visit(aConcreteElement[i])operation()Holub Visitor vsGoF Visitor 1
class Visitor_Car«interface?CarElementVisitor+ visit(Wheel) : void+ visit(Engine) : void+ visit(Body) : void«interface?CarElement+ accept(CarElementVisitor) : voidCarElementPrintVisitorEngineWheelBodyclass Visitor_Holub+ accept(CarElementVisitor) : void+ accept(CarElementVisitor) : void+ accept(CarElementVisitor) : voidv.visit(this)v.visit(this)v.visit(this)Publisher«interface?Distributor+ accept(Distributor) : voidforall node in list+ deliverTo(Object) : void   node.accept(:Distributor);<<anonymous>>Node+ deliverTo(Object) : void- subscriber:  Object((Observer)subscriber).notify();+ accept(Distributor) : voiddistributor.deliverTo(subscriber);Holub Visitor vsGoF Visitor 2
Publisher vsAWTEventMulticasterAWTEventMulticasterAWT의 모든 리스너 인터페이스 구현이벤트 타입이 추가될 때마다 해당 인터페이스에 대한 과도한 코드 수정Publisher임의의 이벤트를 임의의 구독 객체에 출판이벤트 타입 추가 시 코드 증가량이 작음
class GoF_CompositeComponent1..*+ Operation()Client+ Add() : Component+ Remove() : Component+ GetChild() : ComponentLeafComposite+ Operation()+ Operation()-childrenforall g in children   g.Operation();+ Add() : Component+ Remove() : Component+ GetChild() : ComponentGoF – Composite Pattern의도개별 객체와 복합 객체를 동일하게 다루고 싶을 경우
class AWT_ComponentContainerpublic void doLayout(){Component    for( every Component in contents )        doLayout();+ doLayout() : void}0..*1ComponentContainer+ doLayout() : voidButtonLeaf+ add(Component) : ComponentCompositeCheckboxLeafCompositeCompositeWindowCompositeLeafChoiceFrameCompositeDialogCase Study: AWT Component/Container
패턴은 변형되어 실체화된다Composite 패턴의 의도를 보라class Directory SystemLeaf and ComponentSimpleFileComposite+ open()+ close()Composite+ print()Directorypublic void print()0..*{{contents}+ print()    for(int i=0; i < contents.length; ++i)+ add(SimpleFile)        contents[i].print();1+ remove(SimpleFile)}+ contents() : IteratorCase Study: Directory System
VS

More Related Content

PPT
HolubOnPatterns/chapter3_3
PPTX
Fluent Python - Chapter 8
PPTX
190821 delphi
PDF
안드로이드 개발자를 위한 스위프트
PPT
GCGC- CGCII 서버 엔진에 적용된 기술 (1)
PPT
GCGC- CGCII 서버 엔진에 적용된 기술 (2) - Perfornance
PPTX
Jupyter notebok tensorboard 실행하기_20160706
PPTX
Rk charactionbalance다이어그램
 
HolubOnPatterns/chapter3_3
Fluent Python - Chapter 8
190821 delphi
안드로이드 개발자를 위한 스위프트
GCGC- CGCII 서버 엔진에 적용된 기술 (1)
GCGC- CGCII 서버 엔진에 적용된 기술 (2) - Perfornance
Jupyter notebok tensorboard 실행하기_20160706
Rk charactionbalance다이어그램
 

What's hot (20)

PPTX
[하코사세미나]미리보는 대규모 자바스크립트 어플리케이션 개발
PDF
Blockchain 4th dapp programming
PPT
GCGC- CGCII 서버 엔진에 적용된 기술 (4) - Executing System
PDF
Blockchain 3rd smart contract programming
PPTX
Surface flingerservice(서피스 출력 요청 jb)
PPT
GCGC- CGCII 서버 엔진에 적용된 기술 (5) - Executor with Exception
PPT
GCGC- CGCII 서버 엔진에 적용된 기술 (8) - Group System
PPT
GCGC- CGCII 서버 엔진에 적용된 기술 (3) - Exception
PDF
Blockchain 1st bitcoin_core
PPTX
PPTX
만들면서배우는Cocos2d-x(12-13)
PDF
Realm은 어떻게 효율적인 데이터베이스를 만들었나?
PPTX
Surface flingerservice(서피스 플링거 연결 jb)
PPTX
NDC14 - Rx와 Functional Reactive Programming으로 고성능 서버 만들기
PPTX
Startup JavaScript 8 - NPM, Express.JS
PDF
Multithread design pattern
PPT
GCGC- CGCII 서버 엔진에 적용된 기술 (6) - CGCII Server Sample
PDF
Blockchain 2nd ethereum_core
PPTX
Surface flingerservice(서피스 플링거 연결 ics)
PPTX
Surface flingerservice(서피스플링거서비스초기화 ics)
[하코사세미나]미리보는 대규모 자바스크립트 어플리케이션 개발
Blockchain 4th dapp programming
GCGC- CGCII 서버 엔진에 적용된 기술 (4) - Executing System
Blockchain 3rd smart contract programming
Surface flingerservice(서피스 출력 요청 jb)
GCGC- CGCII 서버 엔진에 적용된 기술 (5) - Executor with Exception
GCGC- CGCII 서버 엔진에 적용된 기술 (8) - Group System
GCGC- CGCII 서버 엔진에 적용된 기술 (3) - Exception
Blockchain 1st bitcoin_core
만들면서배우는Cocos2d-x(12-13)
Realm은 어떻게 효율적인 데이터베이스를 만들었나?
Surface flingerservice(서피스 플링거 연결 jb)
NDC14 - Rx와 Functional Reactive Programming으로 고성능 서버 만들기
Startup JavaScript 8 - NPM, Express.JS
Multithread design pattern
GCGC- CGCII 서버 엔진에 적용된 기술 (6) - CGCII Server Sample
Blockchain 2nd ethereum_core
Surface flingerservice(서피스 플링거 연결 ics)
Surface flingerservice(서피스플링거서비스초기화 ics)
Ad

Similar to HolubOnPatterns/chapter3_1 (8)

PDF
NDC 2017 하재승 NEXON ZERO (넥슨 제로) 점검없이 실시간으로 코드 수정 및 게임 정보 수집하기
PPTX
Effective c++(chapter 5,6)
PDF
[야생의 땅: 듀랑고]의 식물 생태계를 담당하는 21세기 정원사의 OpenCL 경험담
PPTX
Api design for c++ ch3 pattern
PPTX
Api design for c++ pattern
PDF
Effective c++ chapter1 2_dcshin
PDF
Nodejs_chapter3
PDF
7가지 동시성 모델 - 데이터 병렬성
NDC 2017 하재승 NEXON ZERO (넥슨 제로) 점검없이 실시간으로 코드 수정 및 게임 정보 수집하기
Effective c++(chapter 5,6)
[야생의 땅: 듀랑고]의 식물 생태계를 담당하는 21세기 정원사의 OpenCL 경험담
Api design for c++ ch3 pattern
Api design for c++ pattern
Effective c++ chapter1 2_dcshin
Nodejs_chapter3
7가지 동시성 모델 - 데이터 병렬성
Ad

HolubOnPatterns/chapter3_1

  • 1. Holub on PatternsChapter 3.1 – Game of Life아꿈사http://andstudy.com안명환http://eritaka.net
  • 2. John Conway’s Game of Life오직 2 가지 법칙죽어 있는 셀은 3개의 이웃이 있으면 살아난다두 개 혹은 세 개의 이웃만을 가져야만 산다
  • 3. 특징 – Game of LifeEmergence하위 수준에는 없는 특성이 상위 수준에서 자발적으로 출현하는 현상미시 동기의 결합으로 인한 거시 행동 형성다양한 패턴 발생
  • 7. class Java Menu SubSyst...JComponent«Property>- name- text+ setName(String) : void+ getName() : String+ setText(String) : void+ getText() : StringAbstractButtonJMenuBar«interface>notifiesActionListener+ addActionListener(ActionListener) : void+ add(JMenu) : void«call?+ actionPerformed(ActionEvent) : void+ removeActionListener(ActionListener) : void# fireActionPerformed(ActionEvent) : voidObserver1SubjectObserverJMenuItemComponent & Leaf+ JMenuItem(String)Concrete ObserverConcrete Subject*Composite{submenus}<<anonymous>>1Composite+ actionPerformed(ActionEvent) : voidConcrete SubjectJMenu+ add(JMenuItem) : void*{menus}Case Study: Menu (Java Swing)
  • 8. Observer 문제구현 상속 기반의 해결안abstract class BadJMenuItem {abstract void itemSelected();}classMyMenuItemextendsBadJMenuItem {public void itemSelected() {//아이템이 선택되었을 때 수행할 것... }}문제점
  • 9. 모든 메뉴 아이템이 BadJMenuItem상속
  • 10. BadJMenuItem을 상속한 개체에만 통지의도객체의 상태가 변경될 때 관련 객체들에게 통지하고 싶을 경우class GoF_Observ...Subject+ Attach(Observer)Observer-observers+ Detach(Observer) : Observer+ Notify() : Observer+ Update()1..*for all o in observers { o->Update()}ConcreteSubjectConcreteObserver- subjectState- observerState-subject+ GetState()+ Update()return observerState = subjectStatesubject->GetState()+ SetState()GoF – Observer Pattern
  • 11. Observer: 멀티스레드 환경 1해결책 1의 문제class Publisher1 {ArrayList subscribers = new ArrayList();// fireEvent를 기다리다가 기아 현상 발생public synchronized void subscribe(Runnable subscriber) {subscribers.add(subscriber);}public synchronized void cancelSubscribe(Runnable subscriber) {subscribers.remove(subscriber);}private synchronized void fireEvent() {for(inti=0; i < subscribers.size(); ++i) ((Runnable)subscribers.get(i)).run(); // 시간이 걸린다!}}
  • 12. Observer: 멀티스레드 환경 2해결책 2의 문제class Publisher2 {private Collection subscribers = newLinkedList();// Iterator연산 중 add, remove 호출 시 예외 발생public synchronized void subscribe(Runnable subscriber) {subscribers.add(subscriber);}public synchronized void cancelSubscribe(Runnable subscriber) {subscribers.remove(subscriber);}private void fireEvent() {for( Iteratori=subscribers.iterator(); i.hasNext(); ) ((Runnable)i.next()).run(); }}
  • 13. Observer: 멀티스레드 환경 3해결책 3의 문제class Publisher3 {private Collection subscribers = newLinkedList();public synchronized void subscribe(Runnable subscriber) {subscribers.add(subscriber);}public synchronized void cancelSubscribe(Runnable subscriber) {subscribers.remove(subscriber);}// 통지 이벤트 시마다 복사본이 생성 (구독취소 이벤트와 상관없이)private void fireEvent() {Collection localCopy;synchronized( this ) {localCopy = subscribers.clone();}for( Iteratori=localCopy.iterator(); i.hasNext();) ((Runnable)i.next()).run();}}
  • 14. Observer: 멀티스레드 환경 4불변 객체 노드를 사용하는 리스트 해결법이전:헤드d:Objectc:Objectb:Objecta:Object이후:가비지 컬렉션 될 것임이전 헤드d:Objectc:Objectb:Objecta:Object헤드
  • 15. class GoF_VisitorVisitor+ VisitConcreteElementA(ConcreteElementA)+ VisitConcreteElementB(ConcreteElementB)ConcreteVisitor1ConcreteVisitor2+ VisitConcreteElementA(ConcreteElementA)+ VisitConcreteElementA(ConcreteElementA)+ VisitConcreteElementB(ConcreteElementB)+ VisitConcreteElementB(ConcreteElementB)ElementObjectStructure1..*+ Accept(Visitor)ConcreteElementAConcreteElementB+ Accept(Visitor)+ Accept(Visitor)v->VisitConcreteElementA(this)v->VisitConcreteElementB(this)GoF– Visitor Pattern의도기존 계층 구조를 수정하지 않고 새로운 메소드를 추가하고자 할 때전문가 도입
  • 16. sd LifeGameVisitorClockpublishersubscribers[i] ::Distributorsubscribers[i].subscriberNodetick()publish(:Distributor)*accept(:Distributor)deliverTo(subscribers[i].subscriber)tick()"visit" 메소드sd GoF_VisitoraObjectStructureaConcreteElement[i]aConcreteVisitor*accept(Distributor)visit(aConcreteElement[i])operation()Holub Visitor vsGoF Visitor 1
  • 17. class Visitor_Car«interface?CarElementVisitor+ visit(Wheel) : void+ visit(Engine) : void+ visit(Body) : void«interface?CarElement+ accept(CarElementVisitor) : voidCarElementPrintVisitorEngineWheelBodyclass Visitor_Holub+ accept(CarElementVisitor) : void+ accept(CarElementVisitor) : void+ accept(CarElementVisitor) : voidv.visit(this)v.visit(this)v.visit(this)Publisher«interface?Distributor+ accept(Distributor) : voidforall node in list+ deliverTo(Object) : void node.accept(:Distributor);<<anonymous>>Node+ deliverTo(Object) : void- subscriber: Object((Observer)subscriber).notify();+ accept(Distributor) : voiddistributor.deliverTo(subscriber);Holub Visitor vsGoF Visitor 2
  • 18. Publisher vsAWTEventMulticasterAWTEventMulticasterAWT의 모든 리스너 인터페이스 구현이벤트 타입이 추가될 때마다 해당 인터페이스에 대한 과도한 코드 수정Publisher임의의 이벤트를 임의의 구독 객체에 출판이벤트 타입 추가 시 코드 증가량이 작음
  • 19. class GoF_CompositeComponent1..*+ Operation()Client+ Add() : Component+ Remove() : Component+ GetChild() : ComponentLeafComposite+ Operation()+ Operation()-childrenforall g in children g.Operation();+ Add() : Component+ Remove() : Component+ GetChild() : ComponentGoF – Composite Pattern의도개별 객체와 복합 객체를 동일하게 다루고 싶을 경우
  • 20. class AWT_ComponentContainerpublic void doLayout(){Component for( every Component in contents ) doLayout();+ doLayout() : void}0..*1ComponentContainer+ doLayout() : voidButtonLeaf+ add(Component) : ComponentCompositeCheckboxLeafCompositeCompositeWindowCompositeLeafChoiceFrameCompositeDialogCase Study: AWT Component/Container
  • 21. 패턴은 변형되어 실체화된다Composite 패턴의 의도를 보라class Directory SystemLeaf and ComponentSimpleFileComposite+ open()+ close()Composite+ print()Directorypublic void print()0..*{{contents}+ print() for(int i=0; i < contents.length; ++i)+ add(SimpleFile) contents[i].print();1+ remove(SimpleFile)}+ contents() : IteratorCase Study: Directory System
  • 22. VS