320 likes | 437 Views
Design Patterns Part I (TIC++V2:C10). Yingcai Xiao 09/10/08. What For How Examples. Outline. Design Patterns (What?).
E N D
Design PatternsPart I (TIC++V2:C10) Yingcai Xiao 09/10/08
What • For • How • Examples Outline
Design Patterns (What?) • Design Patterns (DP) are devices that allow designers to share knowledge about their design. Design patterns identify and abstract common themes in object-oriented design. • idea reuse => code reuse. • UML, C++, DP are used to show, implement, share designs.
Design Patterns (When, Where) • Started in 70’ by Christopher Alexander with two books: A Pattern Language [1977] and A Timeless Way of Building [1979] “Design patterns describe a problem which occurs over and over again in our environment, and then describe the core of the solution to that problem, in such a way that you can use this solution a million times over, without ever doing it the same way twice” • Popularized by the OOPSLA (ACM Conference on Object-Oriented Programming, Systems, Languages, and Applications) • Popular reference book by GoF. Design Patterns: Elements of Reusable Object-Oriented Software by Gamma, Helm, Johnson, & Vlissides http://www.amazon.com/gp/product/0201633612/qid=1133912822/sr=8-1/ref=pd_bbs_1/102-2596010-5604154?n=507846&s=books&v=glance
Design Patterns (When, Where) • The original paper by GoF http://www.cse.msu.edu/~cse870/Materials/Patterns/Docs/orig-patterns-paper.pdf • Tutorials http://www.patterndepot.com/put/8/JavaPatterns.htm http://www.csc.calpoly.edu/~dbutler/tutorials/winter96/patterns/ http://www.cs.wustl.edu/~schmidt/patterns.html
Enforce standards • Encapsulate changes • Prefer composition to inheritance • Do the simplest thing that could possibly work. Characteristics of Good Design Patterns
Interface: a group of headers of public methods of a class; it defines a standardized way of interacting with the class. There are could be more than one interfaces of a class. • Interfaces are commonly used to enforce coding patterns/standards. • Interfaces in Java and C# can not be instantiated. (why?) Any class implementing an interface guarantees to provide the public methods in the interface for others to use. • Any program uses the interface to interact with the class can be reused to interact with other classes implementing the same interface. Enforcing Standards Using Interfaces
There is no “Interface” in C++. • The workaround is to define abstract classes with pure virtual functions. • Pure virtual functions: have only function headers (APIs), but no function bodies. • virtual return-type function-name (argument list) = 0; • Abstract classes: have one or more pure virtual functions; can be used for inheritance by child classes, can not be used for instantiation of objects. The child classes are required to implement all pure virtual functions with predefined APIs. Enforcing Standards Using Interfaces
Example of an abstract class with a pure virtual function: class Command { public: virtual void execute() = 0; }; Enforcing Standards Using Interfaces References on C++ Interfaces http://www.ddj.com/cpp/184410630 http://www.codeguru.com/cpp/cpp/cpp_mfc/oop/article.php/c9989
More on Interfaces • User Interfaces (UI): the interfaces of an application to its users (menus, buttons, …) • Graphical User Interfaces (GUI): a special type of user interfaces which allow users to operate an application by point-and-click. • Application Programming Interfaces (API): interfaces of programming libraries for programmers. E.g. sin and cos in math.lib. • OOP Interfaces: abstract classes used as programming interfaces to enforce coding standards. (OOP API). Methods listed in the abstract classes are APIs. They are all public.
Common task: traversea collection of objects from the beginning to the end. • iterators have been implemented for all C++ collection classes (e.g. vector). • vector<Shape *> shapes; • … • vector<Shape *>::iterator it = shapes.begin(); • while(it != shapes.end()) (*it++)->display(); The Iterator Pattern
MVC Paradigm • A possible way to separate the two aspects (functionality and interface) is using the Model-View-Controller paradigm • model class: contains a number and reports on its primality • view class: presents the user interface • controller class: connect the model and view class
MVC at Work • Apache Structs: • framework for creating Java web applications • free • open source • http://struts.apache.org/ • MS Document-View Architecture: • CDocument • CView • CDocTemplate • http://msdn2.microsoft.com/en-us/library/4x1xy43a(VS.80).aspx
MVC ExampleViswanathan, K.V., “Exploiting Java’s O-O Features,” Java Report, Aug 1999, pp.57-64 • take a number and determine whether it is a prime or not • concentrate on the structure of the code, not the internal mechanism used for checking primality
Designing for Reusability • reuse requires you to think in terms of assembling applications out of components • one approach for this problem: make the user interface distinct from the main functionality
Benefits • you can check for primes using different user interfaces (text, graphical, etc.) • you can use the user interface in other problems that have the same form (in this case, take a number and do something with it)
MVC Paradigm • A possible way to separate the two aspects (functionality and interface) is using the Model-View-Controller paradigm • model class: contains a number and reports on its primality • view class: presents the user interface • controller class: connect the model and view class
Components • design model class so that it is a component which can fit into a framework • the framework then has the capability of incorporating other compatible components (through predefined OOP interfaces) • general guideline: build applications around (OOP) interfaces rather than tying them to specific classes.
Components • (OOP) Interfaces specify (the standards on) how classes should be defined for given applications. • Subclassing (OOP) interfaces to follow the specifications. • Specific classes follow the specifications can create swapable components at runtime. • For MVC we have 3 interface classes to define specifications and 3+ classes for creating concrete swapable components.
MVC Classes has_a has_a
NumberProblemModel interface (listing #2) public interface NumberProblemModel { Object solve(); // solve the problem and re-run the result as an // object void setNumber(int n); // set the number for the problem String getProblemName(); // return the problem name }
MyPrimeTester (listing #3) public class MyPrimeTester implements NumberProblemModel { private int number; public MyPrimeTester() { number = 0; } public MyPrimeTester(int number) { setNumber(number); } public Object solve() { // code to solve problem } public void setNumber(int number) { this.number = number; } public String getProblemName() {return("Primality tester"); } }
NumberProblemView (listing #5) public interface NumberProblemView{ void show(); // present the UI void displayResult(Object obj); void setInputPrompt(String p); // set the prompt that the UI // presents to the user void setOutputDescription(String s); // set the text describing // the output void addListener(NumberListener nl); // set the listener to be // notified of events void setProblemName(String s); }
text user interface class (listing #6) public class NumberProblemTextUI implements NumberProblemView { NumberListener listener = null; String prompt = "", outputDescription= "", problemName = ""; public NumberProblemTextUI() { } protected String getPrompt() { … } public void show() { ... } public void displayResult(Object obj) { } public void setInputPrompt(String prompt) { … } public void setOutputDescription(String description) { … } public void setListener(NumberListener listener) { … } public void setProblemName(String name) { … } protected String getOutputDescription() { … } protected static int readInt() { … } public String getProblemName( ) { … } }
NumberListener (listing #4) public interface NumberListener { void numberEntered(int n); // number has been entered void quit(); // user wants to quit }
NumberProblemController (listing #7) public class NumberProblemController implements NumberListener { NumberProblemView view; NumberProblemModel model; public NumberProblemController(NumberProblemView view, NumberProblemModel model) { … } public void numberEntered(int number) { … } public void quit() { … }
public static void main(String[] args) {(listing #1) if (args.length < 2) { System.out.println("Usage : java NumberProblemController " + "<ViewClassName> <ModelClassName>"); return; } try { new NumberProblemController( (NumberProblemView) Class.forName(args[0]).newInstance(), (NumberProblemModel) Class.forName(args[1]).newInstance()); } catch (Exception e) { System.out.println("Invalid class name supplied"); e.printStackTrace(); } } } // end of class NumberProblemController
NumberProblemGUI (listing #8) public class NumberProblemGUI extends Frame implements NumberProblemView, ActionListener{ public void displayResult(Object obj) { … } public void setInputPrompt(String prompt) { .. } public void setOutputDescription(String description) { … } public void setListener(NumberListener listener) { … } public NumberProblemGUI() { … } public void actionPerformed(ActionEvent ae) { … } public void setProblemName(String name) { … } }
MyFactorAdder (listing #9) public class MyFactorAdder implements NumberProblemModel { public MyFactorAdder() { … } public Object solve() { … } public void setNumber(int number) { … } public String getProblemName() { ... } }