[Skip Navigation] [ CSUSB ] / [CNS] / [CSE] / [R J Botting] / [CS375] [Search ]
[About] [Contact] [Grades] [Objectives] [Patterns] [Projects] [Schedule] [Syllabus]
Session: [01] [02] [03] [04] [05] [06] [07] [08] [09] [10] [11] [12] [13] [14] [15] [16] [17] [18] [19] [20]
[Text Version] patterns.html Wed Mar 10 10:34:03 PST 2010

Contents


    Patterns and Principles

      Good Links on Patterns

      A good list, overview and, discussion of patterns can be found at [ wiki?CategoryPattern ] on the WikiWikiWeb.

      Another source of pattern information is [ Patterns.aspx ] but this is biased towards C# and is an advert for $2,000 courses.

      Here is a nice resource [ http://home.earthlink.net/~huston2/dp/ ] and visual [ patterns.html ] provided by Vince Huston. Here is a quiz [ patterns_quiz.html ]

      The Wikipedia [ http://en.wikipedia.org/wiki/ ] also documents many (if not all) patterns [ Category:Software_design_patterns ] here.

      GRASP -- General Responsibility Assignment Software Patterns

      From Craig Larman [ ../cs375/text.html ]

    1. Expert::=allocate a responsibility to a class that has the information. Look in both the design classes and the domain model to find a type of object that knows enough to handle the responsibility. Knowledge includes having the data, and also knowing who has got the data! Sketch

      [Look for info in the domain]

    2. Creator::=creating an object should be the responsibility of a class that is closely related to the created object. Notice that you always need at least one way of creating an object that doesn't depend on already having an object of that type already. So which class or object is close to the created object. Sketch

      [owners and close friends make good creators]

      Or else you can use a GoF Factory -- a Pure_Fabrication.

    3. Low_coupling::=Assign a responsibilities so that class depends less on other classes using a "need to know basis". Organize responsibilities so that classes do not depend on each other two much.

    4. High_cohesion::=Design elements to have strongly related and focused responsibilities".

    5. Controller::=Assign the responsibility for handling system event messages to a class representing either the whole system, device, or subsystem, or representing the use case /scenario within which the system event occurs. Sketch

      [Possible controllers]

      Compare [ MVC ] (Model-View-Controller). Note: Choose controllers carefully to avoid low cohesion.

    6. Polymorphism::=`Give the same name to services in different objects when the services are similar or related`. Classify objects, using inheritance/generalization, to allow the right version of a service to be executes for the object in question. You can call all your Pets in the same way.... and the Dogs come to you, and the Cats think about it, for example.

      [Class send message to object of right type]

      Example [ Strategy ] in the GOF patterns below.

    7. Pure_Fabrication::=assigning a highly cohesive set of responsibilities to an artificial convenience class that doesn't represent a problem domain concept.

    8. Indirection::=Assign a responsibility to a class that knows where to find an object that can complete the task, Avoid coupling by an intermediate (smart?) object.

      [Put object in the middle]

      You can have indirect access to an abstraction without knowing the precise concrete implementation of the abstraction. Polymorphism makes sure you get the right behavior.

    9. PV::=Protected_variation.
    10. Protected_Variation::=Identify points of predicted variation or instability and assign responsibilities to create a stable interface around them.
      1. Parnas: Separate your design decisions into separate modules. See Parnas.
      2. SDM: Separate physical from logical structures in separate processes.
      3. GoF: Template_Method, Facade, Proxy, Adapter,...

      GoF Patterns

    11. GoF::="The Gang of Four".... see GoF_book and
    12. The_Gang_of_Four::abbreviation={Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides}, Four OO thinkers who wrote an influential book of design patterns.
    13. GoF_book::=following, [Gammaetal94] , note -- uses a pre-UML notation.

      Links on the Gang of Four patterns. THe Wikipedia has articles of varying quality on the GoF patterns. Here [ http://pw.tech-arts.co.jp/download/design_pattern/ ] are some quite good UML diagrams but I'm not sure of the descriptions. And the WikiWikiWeb [ wiki?DesignPatterns ] discusses them all -- but is short of diagrams (if you like diagrams). More links: [click here [socket symbol] if you can fill this hole]

      Many GoF combine two or more GRASP patterns. For example State is a Pure_Fabrication that uses Indirection to protect a class from state changes (PV).

    14. Abstract_factory::GoF=Design a common interface for creating families of similarly or related objects. See Factory. [ wiki?AbstractFactoryPattern ]

    15. Adapter::GoF=Introduce a class to convert the interface of one component into another interface. Think plugs and sockets. make one interface for one or more suppliers. Unlike Proxy, an adapter converts different interfaces into one common one. [ wiki?AdapterPattern ] [ PatternAdapter.aspx ] [ fig25_25_1.cpp ] [ test.fig25_25_1.cpp ] (From Larman05)

    16. Bridge::GoF=A class of objects that acts as an interface between clients and an implementation. Unlike an Adapter the bridge connects to a family of objects with the same operations. [ wiki?BridgePattern ] [ bridge_s.jpg ] [ Bridge_pattern ]

    17. Builder::GoF=How to constuct complex objects with varying parts? A director calls various builders as needed, a variation on the Factory patterns. [ Builder_pattern ] [ wiki?BuilderPattern ]

    18. Command::GoF=Design objects that know how to do (and undo) a family of tasks and pass them to other objects to be used as needed. [ wiki?CommandPattern ]

    19. Composite::GoF=Make complex and simple kinds of an object share behavior. And often the complex objects keep a list of their parts: each of which is a similar kind of object. [ wiki?CompositePattern ] [ PatternComposite.aspx ]

    20. Decorator::GoF=A class can take an object and wrap new functions around it. [ decorator.gif ] [ TestDecorator.java ] [ wiki?DecoratorPattern ]
    21. Wrapper::=Decorator.

    22. Facade::GoF=A class or object provides a single point of entry for services of a subsystem, Hide a complex system of objects behind a single object. Pay no attention to the man behind the curtain. [ wiki?FacadePattern ] [ PatternFacade.aspx ] [ Facade_pattern ]

    23. Factory::=an object/operation/class is designed solely to create other kinds of object. A factory is an alternative to a constructor in a class. Because it is a member of a different class (the factory) we can get objects without having to know precisely what class they are instances of. Other patterns need the ability to create concrete implementations of an abstraction -- but without knowing which implementation has been chosen. This is not a GoF pattern, see Abstract_factory, FactoryMethod, and Builder.

    24. FactoryMethod::=an operation that creates an object. Typically there is a hierarchy of classes all providing the same operation to create objects of different types. Similarly the resulting object should be a specific object in a hierarchy of products.

    25. Observer::GoF=An object that implements the operations that let it subscribe to learn about other objects. Objects that need to see what an object is doing can join a collection maintained by the observed object. These are subscribers. The observed object publishes the changes to the subscribers using one or more special operations that a listed in an interface that the observers all implement. It is also possible for an object to subscribe other objects as observers. [ Observer.gif ] (Class diagram) [ observer.png ] (sequence diagram) [ wiki?ObserverPattern ] [ PatternObserver.aspx ]

    26. Proxy::GoF=Design an object that can stand in for other objects and knows which object it is representing and how to simulate it. As a result we can change the real object with out breaking the client. [ proxy.gif ] [ wiki?ProxyPattern ]

    27. Singleton::GoF=To make sure that there is precisely one object in a class and provide access to it. [ wiki?SingletonPattern ] [ PatternSingleton.aspx ] [ singleton.cpp ] [ test.singleton.cpp ]

    28. Strategy::GoF=Place different ways to do something behind a common interface and use indirection via an object to pick the right one. [ Strategy.gif ] [ wiki?StrategyPattern ] [ PatternStrategy.aspx? ]

    29. State::GoF=When an object changes behaviors (responsibilities) with time, place the state in a different State object and place the different behaviors in special kinds of State object. Note: in most programming language can not change its class! Also note that an efficient State implementation can use Singleton for the states. [ wiki?StatePattern ] (on the WikiWikiWeb). Examples: [ StatePatternExample.html ] [ test.State.cpp ] [ State.cpp ] (using lazy Singleton and a "call back") OR [ State2.cpp ] (using eager Singleton, breaking CQS principle, and hiding the initial state) [ test.State2.cpp ] , Exercise: redraw the UML diagram to show the changed classes between State and State2.

    30. Template_Method::GoF=A method in a class can use abstract operations (hooks) that are defined in a subclass so that the subclass provides some functionality while using the overall method. The classic example is a method that sorts a vector of data in a Sortable class but uses an undefined "less_than" operation. Other classes extend the Sortable and define "less_than" and can then sort the data Their way, right away. [ wiki?TemplateMethodPattern ] This result is also called a Framework.

    31. Flyweight::GoF=when you have lots of small similar objects keep exemplas ina data structure and point to those for the details. [ wiki?FlyweightPattern ] [ Flyweight_pattern ] Classic example: characters in wordprocessing. Used for State and Strategy. Used with Composite.

      Analysis Patterns

      Bolloju04

      1. Narasimha Bolloju
      2. Improving the quality of business object models using Collaboration patterns
      3. Commun ACM V47n7(Jul 2004)pp81-86 [ 1005817.1005827 ]
      4. =EXPERIMENT MODEL REALITIES PATTERN UML COMPOSITION
      5. Based on Coad and Fowler lists 12 simple patters that helped students improve their conceptual models in 13 different business application domains: spotting classes and connections, plus correcting errors.

        (Figure 1 is in ASCII below)

      6. Collaboration_patterns::#Pattern=following,
        • E1: Role (1)-(0..*) Transaction
        • E6: Transaction (1)-(0..*) FollowupTransaction
        • E5: Specification (1)-(0..*) Transaction
        • E3: CompositeTransaction (1)<*>-(0..*) LineItem
        • E2: Place (1)-(0..*) Transaction
        • R: Actor (1)-(0..*) Role
        • T1: Item (1)-(0..*) SpecificItem
        • T4: Group (1)<>-(0..*) Member
        • E4: SpecificItem (1)-(0..*) Transaction
        • T2: Assembly(1)<*>-(0..*) Part
        • P: OuterPlace (1)-(0..*) Place
        • T3: Container (1)<*>-(0..*) Content
      7. Next [BollojuLeung06]

      Domain Model Patterns

      [Wagner05] [ domainPatterns.png ]

      XP Principles

    32. DRY::=Don't repeat yourself.
    33. YAGNI::=You Aint' Gonna Need It. When in doubt leave it out! Keep It Simple, Stupid!

      Persistence Principles

    34. tables::=All data can be expressed by a collection of simple tables.

    35. Persistence_as_a_superclass::=`Put all the persistence code into a superclass and then any class can become persistent by inheriting from the persistence class`. Notice that this can get clumsy and in Java foul up more important extensions.

    36. ACID::principle="Atomic, Consistent, Isolated, and Durable". Jim Gray's ACID principles of Data Base transactions.
      • atomic::=a transaction either completes or does nothing. -- no interrupts.
      • consistent::=a transaction never leaves the data in a state that breaks the rules. A marriage has two people: no more, no less.
      • isolated::=The effect of a transaction is hidden from other transactions until it is complete.
      • durable::=A transaction, once completed, is never lost -- even if things break down or fail.

    37. database_mapper::=The class of the object determines what data needs to be stored so define objects for each class to handle the tables.

    38. cache_management::=Databases should manage their own caches.

    39. hide_SQL::=Put all the SQL in one object -- a singleton -- and keep it separate from the rest of the code. Treats SQL as an external entity with its own secrets. See Parnas.

      Exception Principles

    40. Convert_exceptions::=If you can not handle an exception then convert it to a higher level exception.
    41. Name_the_problem_not_the_thrower::=name exceptions to indicate what is wrong not where it came from.
    42. centralize_error_logging::pattern. Have a single object that is responsible for recording bad things.
    43. standard_error_dialog::pattern. Have a standard user interface for reporting and sorting out errors.

      OO Principles

    44. IDs_to_Objects::="An object is more than its ID or Key and more useful", so when you are given an identifier or key you should replace it by the correct object as soon as possible, for example by a Controller.

      [Controller asks creator to convert ID to Object]

    45. OO::=Object Oriented Principles, including abstraction, extension, polymorphism, etc.

    46. OID::=Objects should know their own identity... and this can be expressed as a simple data item and stored in data tables, and hidden from the user.

    47. abstraction::OO=Variables and parameters should be declared as reference or pointers to abstract data types whenever possible, and containers as holding pointers to abstractions. Also known as Aim high -- allow your pointers to refer to abstractions and then they can point to many special kinds of object. For example(in C++):
      1. Declare variable abstract and assign address of concrete:
         		List * example = new SpecialKindOfList(....);
         		Person * dick = new Faculty(....);

      2. Declare parameters as refs to abstractions
         		void zark(List &w){....}
      3. Declare containers as containing pointers to abstractions:
         		map<string, Person*> people;
         		people.insert(string("Dick"), dick);

    48. extension::OO=Extend classes rather than reinventing the wheel.

    49. polymorphism::OO=let objects sweat the details for you. See GRASP Polymorphism

      Other Principles

    50. Parnas::=place different decisions in different modules, for example
      • 1971: Put input, output, and logic in separate modules that communicate by function calls.
      • Separate the physical from the logical.
      • Hide a data structure inside an Abstract Data Type.
      • Hide an algorithm behind a Strategy.
      • Hide external systems behind a Facade.
      • Hide libraries behind a Facade or an Adapter.
      • Hide SQL inside a package or object (hide_SQL).
      • Hide the User inside a User_interface (UI) Package.
      • Separate particular Applications from Business Logic and Domain.
      • Separate Model, View, and Controller. See MVC
      • Hide a RDBMS behind a simple OO persistence layer.

    51. CQS::=Command_Query_Separation,
    52. Command_Query_Separation::principle=Operations should either do something and return nothing or return something and do nothing, NOT both,
      1. void doSomething(data);// nothing returned
      2. Type getSomething(data);//leaves everything the same.

      This dates back to the the theory of abstract data types and was inherited by Meyer into objected oriented coding style. This principle leads to code that is slightly more verbose but very much clearer. It also reduces bugs by the principle of Least_Surprise.

    53. Least_Surprise::principle=`Whenever you design anything choose a design that minimizes the surprises that the user may experience`. Henry Ledgard proposed this for programming languages but it also applies to user interfaces, common appliances, and object-oriented classes. Apple had a tendency to extend so that the user experiences occasional pleasant surprises: the user does the wrong thing and the system does the right thing. This is also called
    54. DWIM::="Do What I Mean". This is a dangerous philosophy because it back fires.

    55. Model_View_controller::pattern=MVC. [ mvc.gif ]
    56. MVC::pattern="Model-View-Controller",
        This patterns suggests separating the logic of the data (Model) from the code that interfaces with the user (View+Controler).
      • Separate Model (data + ...) from View(what the user sees...) from Control (what the user can do...). [ MVCinUML.gif ] (UML diagram of View, Controller and Model packages)
      • In some methods yo split Boundary, Control and Entity objects. And use special icons for them: [ icons.gif ] (Graphic showing common icons and stereotypes).

        The code that describes user interfaces is independent of the code for the logic of an enterprise or application. The appearance of the user interface for a pay-roll should be separated from the rules for calculating your with-holdings. Neither should the choice of the user interface framework change the calculations. So the wise designer splits all the user interface code into specialized classes that communicate with the application specific classes. This is splitting the users "View" from the logical "Model". As a result the "Model" classes can reflect the Domain or Business model and so are easier to understand and get right... and keep right.

        As a result you can change the View (add a new one, rip out the AWT and put in Swing, ...) without worrying about the payroll logic.

        Here is a paper [ 1121341.1121453 ] that has a set of Java programs that access a time server and show the user the time of day found on that server. One program has a command line interface, one has a menu driven ASCII interface and one a GUI interface, but they share a common "model" of how to access the time server. This class never changes... each interface is implemented as a new class that uses the model:

        View -> Model

        The diagrams in the paper are not correct UML, do not use them!

        In general, there are lots of classes defining the user interface and many classes in the Model. In the UML use packages to contain them.

        More strictly the user interface code is split into two sets of classes. The View and the Controler. Typically the user communicates with controlers that change the model. The view classes get data from the model and are responsible for rendering it to the user.

         		User ---> Controler ----> Model -----> View -----> User

      • Also see [ Model-view-controller ] for the history and a list of frameworks that use MVC.

    57. FURPS+::requirements={Functional, Usability, reliability, Performance, supportability, Implementation, Interface, Operations, Packaging, Legal}, Grady92.

    58. KISS::=Keep It Simple, Stupid, see XP.YAGNI. "Do the simplest thing that could possibly work."

    59. PQRST::requirements={Purposes, Qualities, Realities, Systems, Techie}, from RJB.
      Net
      1. Purposes include functions and use cases and define why someone wants the software. To help us sell items to customers.
      2. Qualities are the needed properties of the software like security and performance criteria.
      3. Realities are domain models. We have the problem of integrating different views of the the real world
      4. Systems are the existing systems that we are replacing, using, modifying, and even competing with.
      5. Techie include technologies, techniques, etc. and describe what and how we might construct the software -- the decisions we make: eg.-- use VB and MySQL.

      (End of Net)

    60. The_Hollywood_Principle::pattern="Don't call us, we will call you", This is a common implementation pattern for interacting with a framwork or operating system. Instead of the program calling the operating system when it needs to something, it waits to be called by the environment when events happen. Detail at [ Hollywood_Principle ] on the Wikipedia. The GoF Observer pattern uses the Hollywood Priciple. The classic GoF State pattern uses it to change the state.

      AntiPatterns -- Patterns that occur but don't resolve the forces well

        The Ball of Mud Pattern

        You should read and study this an excellent, short, and readable blog entry [ 001003.html ] describing the ways in which system and software architecture goes astray and ultimately becomes unmanageable.

    . . . . . . . . . ( end of section Patterns and Principles) <<Contents | End>>

    Standard Definitions

  1. DCD::diagram="Design Class Diagram", shows the classes that will be implemented in code.
  2. Glossary::= See http://cse.csusb.edu/dick/cs375/uml.glossary.html.
  3. GoF::="Gang of Four", [ patterns.html#GoF ]
  4. GRASP::patterns="General Responsibility Assignment Software Patterns", a set of guidelines for designing objects and classes. They take a single event that the system must handle and determine a good class to carry it out. See [ patterns.html#GRASP -- General Responsibility Assignment Software Patterns ]
  5. Grades::= See http://cse.csusb.edu/dick/cs375/grading/.

  6. KISS::Folk_law="Keep It Simple, Stupid", in agile processes this means never drawing a diagram or preparing a document that doesn't provide value to the clients and stakeholders. In all processes it means never designing or coding what is not needed, see YAGNI.

  7. OO::shorthand="Object-Oriented".

  8. OOAD::="Object-Oriented Analysis and Design", See chapter 1 in text.
  9. patterns::="Documented families of problems and matching solutions", see Patterns.
  10. Patterns::= See http://cse.csusb.edu/dick/cs375/patterns.html.

  11. Process::="How to develop software".

  12. RJB::=The author of this document, RJB="Richard J Botting, Comp Sci Dept, CSUSB".
  13. RUP::Process="Rational UP", a proprietary version of UP.

  14. SSD::="System Sequence Diagrams", see chapter 10.

  15. TBA::="To Be Announced".

  16. UML::="Unified Modeling Language". [ Unified_Modeling_Language ]

  17. UP::="Unified Process", an iterative, risk-driven, and evolutionary way to develop OO software.

  18. YAGNI::XP="You Ain't Gonna Need It", an XP slogan that stops you planning and coding for things that are not yet needed. As a rule the future is not predictable enough to program a feature until the stakeholders actually need it now. In this class it means "It won't be on the final or in quizzes".

  19. XP::="Extreme Programming", the ultimate iterative code-centric, user-involved process.

End