700 likes | 809 Views
Pattern Story (for .NET Developers). YoungSu, Son only2u4u@devpia.com Microsoft MVP Devpia Architecture&Design Sysop Devpia .NET Framework 3.0 Sysop Samsung Electronics Home Solution Group. Agenda. Pattern and Model with Etymon. GoF 2 Principles. Basic Patterns with .NET
E N D
Pattern Story(for .NET Developers) YoungSu, Son only2u4u@devpia.com Microsoft MVP Devpia Architecture&Design Sysop Devpia .NET Framework 3.0 Sysop Samsung Electronics Home Solution Group
Agenda • Pattern and Model with Etymon. • GoF 2 Principles. • Basic Patterns with .NET • Strategy Pattern • Template Method Pattern • Component Configuration Pattern • Reflection Pattern • Pipe & Filter Pattern • Factory Pattern • Observer Pattern • Chain-of-Responsibility Pattern • Relationship between Patterns. • Introduce to Pattern Explore & Books Devpia A&D EVA
What’s the Design Patten? Dessin Pattern is Father! The Definition of Design Pattern Model is Mother Pattern & Model Devpia A&D EVA
Dessin 데셍하다 살짝 밑그림을 그리는 작업 Design de = away sign = Note 완성품을 만들기 이전에 살짝 뼈대를 잡는 작업 Dessin
Pattern의 어원은 Father(아버지) 에서 파생 비슷한 생김새, 성격등을 가지고 있음을 의미 그럼 비슷한 문제들도 비슷한 방법(Pattern)으로 해결 가능 Pattern is Father
The Definition of Design Pattern 좋은 S/W의 밑 그림을 잘 그릴수 있는 지침/가이드라인
GoF 2 Principles • Program to an interface, not to an implementation • Favor Object Composition over Class Inheritance Devpia A&D EVA
GoF 1st Principle.Program to an interface, Not to an implementation. • When you pick up your rental car.. • Push the seat all the way back • Find an NPR station • Find the exit • Read the Manual?
Why you don’t read rental car manuals • You know how to drive your car • All cars work basically the same way • Your rental car is a car • Therefore, you can drive your rental car • That is… The Power of Sameness
Only use Object Composition! A swindler GoF 2nd PrincipleFavor Object Composition over Class Inheritance Don’t use Inheritance?? Developer
A Great Architect The Two Towers in Object World. Composition & Inheritance are Two Towers in OO World
Interview Design Principles from Design Patterns Eric Gamma Say A common misunderstanding is that composition doesn’t use inheritance at all. Refers http://www.artima.com/lejava/articles/designprinciplesP.html Composition versus Inheritance. Eric Gamma
Don’t use Subclassing Interface1 Impl. +ISomething() +ISomething() Impl Inheritance Impl Inheritance Concrete Class2 Concrete Class1 +ISomething() +ISomething() +ISomething() +ISomething() A Great Architect Types of Inheritance. Subtyping Subclassing Class Impl { ISomething() { .. do(); .. } } Class Interface1 { ISomething() = 0; }
GoF 2nd Principle. • 1990’s • Favor Object Composition over Class Inheritance. • 2000’s • Favor Object Composition (based SubTyping) over SubClassing.
SortAlgorithm Sort() BubbleSort Sort() QuickSort Sort() UltraSort Sort() DataArray SortAlgorithm* m_pSort SetAlgorithm(SortAlgorithm* pSort) Sort() Principles of GoF Pattern 객체합성 상속(subtyping)
Basic Patterns Core Components of SW Impl. Strategy Pattern Template Method Pattern Component Configurator Pattern Reflection Pattern Pipe & Filter Pattern Factory Pattern Observer Pattern Chain of Responsibility 9/3/2014 Devpia A&D EVA 23
Core Components of S/W Impl. Great Architect You must remember 3 Core Components! Common Part Variable Part Configurable Part 9/3/2014 Devpia A&D EVA 24
Core Components of S/W Impl. AOP Variable Part Common Part (Modularity) Strategy <<CREATES>> Factory Log Configurable Part Security <<LINKS>> Transaction Component Configurator 9/3/2014 Devpia A&D EVA 25
Strategy Pattern • Intents Do you think that the same logic use between satellite and super computer? satellite Super Computer Devpia A&D EVA
void main() { //pSort라는 인터페이스를 선언한다 CSort *pSort; if (GetSystemInfo() == Low) { //인공위성에서는 Bubble Sorting 사용 pSort = new CBubble(); } else { //슈퍼 컴퓨터에는 Quick Sorting 사용 pSort = new CQuick(); } pSort->Sorting(); delete pSort; } CSort +Sorting() CBubble CQuick +Sorting() +Sorting() Strategy Pattern in GoF Devpia A&D EVA
Template Method Pattern • Intents Application ODBC(JDBC) API ODBC (JDBC) Driver Manager MSSQL Driver Oracle Driver Devpia A&D EVA
CQueryTemplate +doQuery() #FormatConnect() #FormatSelect() COracleQT CSqlSvrQT Inversion of Control (Hollywood Principle) #FormatConnect() #FormatSelect() #FormatConnect() #FormatSelect() Template Method Pattern in GoF class CQueryTemplate { public void doQuery() { string dbCommand; dbCommand = FormatConnect(); dbCommand = FormantSelect(sql); } ... } void main() { //pQT라는 인터페이스를 선언한다 CQueryTemplate *pQT; Sql sql = “select * from AA”; if (GetDBProductInfo() = Oracle) pQT = new COracleQT(); else pQT = new CSqlSvrQT(); pQt->doQuery(sql); delete pQt; } Devpia A&D EVA
Great Architect Component Configurator Pattern When Change Config File Info, Component Configuration (Attribute) dynamically Changes! • Intents Text Based Log Component XML Based Log Component DES RSA HTTP Protocol FTP Protocol Configuration File Devpia A&D EVA
Component Configurator in POSA2 Component Component Repository +Init() +Fini() +Suspend() +Resume() +Info() Component Configurator CoreComponent CoreComponent Devpia A&D EVA
Component Configurator in POSA2 Devpia A&D EVA
<xml version =“1.0”> <Components> <!– Protocol 정보 선택 --> <Protocol> HTTP </Protocol> <!– Log 정보 선택 --> <Log> XML </Log> <!– 보안 알고리즘 선택 --> <SecuAlgorithm> DES </SecuAltorithm> </Components> void main() { CMessage *pMessage = new CMessage(); if (GetComponentInfo(“Sort”) = HTTP) pMessage->Protocol = HTTP; else pMessage->Protocol = FTP; if (GetComponentInfo(“Log”) = XML) pMessage->Protocol = XML; else pMessage->Protocol = TEXT; ... pMessage->Send(“Hello”); delete pMessage; } Advanced Topic Reflection Component Configurator Sample Devpia A&D EVA
Component Configurator Example • App.config/Web.config In App.config. <?xml version="1.0“ encoding="utf-8" ?> <configuration> <appSettings> <add key="sqlCon" value="컨넥션 스트링 정의"/> </appSettings> </configuration> In C# Code. System.Configuration.ConfigurationSetings.AppSetting[“sqlCon”];
Reflection Pattern in POSA1 Meta Level further meta-level components modifies MetaObject A MetaObject B MOP modifies retrieves information uses uses uses uses Component A Component B UserInterface further base-level components provides access to Base Level
Reflection ModuleBuilder AssemblyModule = CreatedAssembly.DefineDynamicModule("MathModule","Math.dll"); TypeBuilder MathType = AssemblyModule.DefineType("DoMath", TypeAttributes.Public | TypeAttributes.Class); System.Type [] ParamTypes = new Type[] {typeof(int),typeof(int) }; MethodBuilder SumMethod = MathType.DefineMethod("Sum", MethodAttributes.Public, typeof(int), ParamTypes); ParameterBuilder Param1 = SumMethod.DefineParameter(1,ParameterAttributes.In, "num1"); ParameterBuilder Param2 = SumMethod.DefineParameter(1,ParameterAttributes.In, "num2"); . . . MathType.CreateType(); return CreatedAssembly;
Reflection using System; using System.Reflection; ... public class EmitDemoTest { static void Main() { ... System.Type MathType = EmitAssembly.GetType("DoMath"); object[] Parameters = new object [2]; Parameters[0] = (object) (5); Parameters[1] = (object) (9); object EmitObj = Activator.CreateInstance (MathType,false); object Result = MathType.InvokeMember("Sum", BindingFlags.InvokeMethod ,null,EmitObj,Parameters); Console.WriteLine("Sum of {0}+{1} is {2}", Parameters[0],Parameters[1],Result.ToString()); Console.ReadLine(); } }
Protocol Pipeline Read Request Filter svc() svc() svc() Log Request Filter Parse Headers Perform Request svc() perform() svc() parse() svc() parse() svc() log() Pipe & Filter Pattern in POSA1 InputOutput Handler Protocol Handler io pipe component component->svc() io->receive_data() Filter::svc() parse() Filter::svc() perform() Filter::svc() log()
GET image/gif CONNECTION Keep-Alive ACCEPT USER_AGENT image/jpeg /users/jxh/public_thml/home.html ACCEPT Mothra/0.1 */* HOST HTTP /1.0 ACCEPT any.net Read Request Parse Request Parse Headers GET /~jxh/hoem.html HTTP/1.0 Connection: Keep-Alive User-Agent: Mothra/0.1 Host: any.net Accept: image/gif, image/jpeg, */* Using Pipeline HTTP/ 1.0 200 OK Date: Thu, 09 Oct 01:26:00 GMT Server: Eva/1.0 Last-Modified: Wed, 08 Oct 1997 .. Content-Length : 12345 Content-Type : text/html <HTML> <TITLE> Homepage </TITLE> .. </HTML> Perform Request Log Request any.net - - [09/Oct/1997:01:26:00 -0500] “GET /~jxh/home.html HTTP/1.0
Contract To Type Behavior CLR Type Integration Behavior Error Handling Behavior TCP Transport Channel HTTP Transport Channel TCP Transport Channel UDP Transport Channel Queue Transport Channel HTTP Transport Channel UDP Transport Channel Throttling Behavior Transaction Behavior Instancing Behavior Instancing Behavior Custom Behavior Metadata Behavior Custom Behavior Custom Channel Security Channel Security Channel Custom Channel Full Duplex Channel Reliable Messaging Channel Reliable Messaging Channel Concurrency Behavior Cross-Proc Transport Channel Pipe & Filter in WCF Services Runtime Layer Messaging Layer Behaviors Channels
Factory Pattern • Intents Main Function Based Coding Object Oriented Programming Devpia A&D EVA
Factory Pattern (Abstract Factory) • Intents Advanced OO Design OO Design Devpia A&D EVA
Client Abstract Factory Abstract Product +CrateProduct() Concrete Factory Concrete Product Factory Pattern in GOF void main() { CMessage *pMessage = new CMessage(); if (GetComponentInfo(“Proto”) = HTTP) pMessage->Protocol = HTTP; else pMessage->Protocol = FTP; if (GetComponentInfo(“Log”) = XML) pMessage->Protocol = XML; else pMessage->Protocol = TEXT; ... pMessage->Send(“Hello”); delete pMessage; } Devpia A&D EVA
Client Abstract Factory Abstract Product +CrateProduct() Reminds Component Configurator!! Concrete Factory Concrete Product Factory Pattern in GOF class CFactory { CMessage* GetInstance() { CMessage *pMessage = new CMessage(); if (GetComponentInfo(“Proto”) = HTTP) pMessage->Protocol = HTTP; else pMessage->Protocol = FTP; if (GetComponentInfo(“Log”) = XML) pMessage->Protocol = XML; else pMessage->Protocol = TEXT; ... return pMessage; } } Devpia A&D EVA
Strategy <<CREATES>> Factory <<LINKS>> Component Configurator 3 Foe Patterns Variable Part Common Part (Modularity) Log Configurable Part Security Transaction Devpia A&D EVA
1. Observation 2. Notification Observer Pattern (Misconception) Misconception!! Or Prejudices (편견!) Change Data Devpia A&D EVA
Observer is Notifieer!! Observer in Observer Pattern is Notifieer Devpia A&D EVA
Hollywood Principle Don’t Call us!! Manager Applicants Devpia A&D EVA
Hollywood Principle Don’t Call us! We Call You!!! Manager Applicants Devpia A&D EVA
1. Change 2. Change 3. Notification Flow of Observer Pattern Change Data Manager Client (Source) Observer is Notifieer Client (Type1) Client (Type2) Client (Type3) Devpia A&D EVA