Module 2

Pataasin ang iyong marka sa homework at exams ngayon gamit ang Quizwiz!

benefits of using strategy pattern

+ Defines a family of related algorithms/behaviors to reuse. + An alternative to sub-classing and inheritance + Strategies eliminate conditional statements like having switch cases inside the algorithm implementation. The case statement will be eliminated by delegating the task selection to a Strategy object. + Strategies can expose to client different implementations of the same behavior.

positive consequences

+ It isolates concrete classes. - It helps to control the classes of objects that an application creates. Factory encapsulates the responsibility and the process of creating product objects and isolates clients from implementations. + It makes exchanging product families easy. - It is easier to change the concrete factory an application uses. - The concrete factory appears only once in your application, where it's instantiated. + It promotes consistency among products. - When objects in a family/group are designed to work together. It is important that an application use objects from only one family at a time.

negative consequences

- Supporting new kinds of products is difficult. - Extending "abstract factories" to produce new kinds of Products isn't easy. That's because the Abstract Factory interface fixes the set of products that can be created. (Think about solutions for this! )

consequences - negative

- Unexpected updates. Any changes in Subject cause lots of push events in Observers and Observers have no knowledge about what exactly is changed there. Without additional protocol to help observers discover what exactly is changed, observers are forced to work hard to deduce the changes.

when to use the observer pattern

- a change to one object requires changes in others so that the changes needed to be forwarded to others, specially when you don't know how many objects need to be changed. - an object should be able to notify other objects without having knowledge about them and being able to make assumptions about them. Simply, you don't want these objects be tightly coupled. - an abstraction has two aspects, one dependent on the other. We can encapsulating the aspects in separate objects so that we can vary them and reuse independently

Example use cases for Observer pattern

-Sensor-based systems (like monitoring systems): --Systems that produce data by using sensors. --The data needs to be sent to other components to process and shown on multiple devices. - Chatrooms: a new message in the chat room needs to be broadcasted to all participants - Online Forums and Group Social Networks, like twitter, facebook, youtube,... Online Services like Uber, Lyft,... The problem is very common."Observer Pattern" has verity of applications.

types of design patterns:

....

design pattern

A design pattern is a general reusable solution to a commonly occurring problem within a given context in software design. Patterns are formalized best practices that the programmers should use and implement in the applications.

abstract factory pattern

A factory is the instantiation of an object by means of a method rather than a direct new operation. In effect, the method incorporates object creation in its code. In this case, we introduce a KitchenStyle class with factory methods getWallCabinet() and getFloorCabinet(). To coordinate the various styles, we subclass KitchenStyle. That way, you can write the rendering software once, using KitchenStyle, and when the user picks a style, this is instantiated as an instance of the appropriate subclass (ModernKStyle, for example). So whenever the code calls for getWallCabinet(), the right kind will be constructed.

observer design purpose

Arrange for a set of objects to be affected by a single object. -clients interact with (an instance of a subclass of) Source, typically changing one of its values. This triggers notify() on Source, and the latter calls all of the update() methods. Observer's need a reference back to the Source object in order to know its new attribute values.

drawbacks of using strategy pattern

Clients must be aware of different Strategies. Use strategy only when the variation in behavior is relevant to clients. - Communication overhead between Strategy and Context. Interfaces are shared among all strategies, info is passed through interfaces. - Increased number of objects

Advantages of using design patterns

Flexibility Understandability Modularity Better Code Reuse Reducing the number of code lines Hiding Complexity ... and many others

loosely coupled design patterns

Loosely coupled designs allow us to build flexible object-oriented applications that can push updates and handle changes because they have reduced the interdependency level between objects.

In general patterns have 4 main elements:

Pattern Name Problem Description Solution and Structure of it Consequences when using the solution

first solution to the problem

Polling solution. Have a reference to the "event" publisher and call a method to get as a return value the event.l Ask if there is any update in time intervals loops l l Disadvantages: - Wasting of resources if there is no change - We can not get the notification in time because we have to wait until time out is reached and ask again.

use case problem (why to use observer pattern)

Sometimes in our application a component has data about - things that are happening frequently like events - data items that will be repeatedly generated like sensor data - object states that are changing frequently And we need to inform multiple parties. problem is: want to get the daily paper. instead of periodically going to my door to continually check if the paper has been delivered. theres a lot of overhead with this scenario. ex: have a website that checks for apple stock every 5 minutes to see if it changed. and your system changes from the value that's changed. lot of overhead going to continually check the stock. its inefficient. solution is instead of polling (checking if something has changed in the stock). Instead better to notify the person when the paper arrives or when the stock has changed. not polling the data, the data gets pushed to the user immediately. Observer pattern has to do with efficiency primarily. but its also very clean and easily maintainable.

strategy pattern problem

Sometimes in your application you have similar objects with different behaviors and you want to have flexibility to manage the behaviors. want to organize similar objects in a heirarchy, bc similar attributes and common methods. and u want your software to select diff computations dynamically at runtime. have flexibility at runtime to choose based on the type of object which should be executed.

problem factory method

Sometimes one of our application classes only knows when a new object should be created, but not which specific sub- type of that object should be created. l In some cases, instantiation is complex and you might need to setup do some settings/configurations to create objects. l You want to have the creation of objects flexible. generates objects for us and we dont care about complexity get objects of a particular type without knowing exactly how its created. if you include subprocesses: a checking account can include internal processes on the bank to create a new account for you. hide complexity from the outside and create the type on the inside. generation of object happens in subclass. calling constructor of that subclass. factory method delegates the responsibility to another class and inside the other class is a method called factory method and that factory method knows which subclasses should be created.

use the observer pattern

The Observer Pattern defines a one-to-many dependency between objects so that when one object changes state, all of its dependents are notified and updated automatically. l Observers delegate the responsibility for monitoring for an event to a central object named "the Subject" or the "Observable".

consequences - positive

The observer pattern lets the programmer vary subjects and observers independently. Subjects can be reused without reusing their observers, and vice versa. Observers can be modified without changing the subject or other observers. + Abstract coupling between Subject and Observer. + Support for broadcast communication.

abstract factory design pattern

This coordinated factory idea does not just apply to kitchen apps, of course, but to any situation where subtypes must be coordinated in what amounts to "styles." Hence the Abstract Factory design pattern shown in the figure. Now the client code needs to know only about styles and the base classes rather than all of the lowest level components. (The figure does not show dependencies of Client with Style1 and Style2, which may be necessary too.)

when to use abstract factory pattern

Use Abstract Factory Pattern when - your application should be independent of how its products are created, composed, and represented. - your system should be configured with one of multiple families of products. - a family of related product objects is designed to be used together, and you need to enforce this constraint. - you want to provide a class library of products, and you want to reveal just their interfaces, not their implementations.

strategy pattern - naive solution

We can hard-code different behaviors and implement them in a long "IF THEN ELSE" statement or SWITCH statement. •The problem is that adding or removing new behaviors requires changing the IF or SWITCH statement. •Instead if IF statement we can use the strategy pattern. using conditional statements to switch bw them. issue is when this heirarchy gets large and long if statement, gets difficult to manage. a set of classes that are all really similar except for one thing

solution

Whenever we have any updates we will inform the interested parties (subscribers). • Push vs. Poll Pushing the new events from the publisher to subscribers.

strategy pattern - implementation

You need a class that uses the algorithm/context contain an abstract class (strategy) including an abstract method to call the algorithm. • Then each derived class implements its own algorithm.• Note: the method is abstract because you wanted to have different behavior. • Note: the responsibility for selecting the particular implementation is done by the client object and passed to the context.

what to learn about each pattern:

You should know 1. When to use the pattern? 2. Why to use the specific pattern? 3. How to use the pattern solution? 4. What are Pros/Cons? 5. What are other related patterns?

most patterns have 2 levels, what are they?

abstract and concrete

behavioral patterns

capture behavior

Observer Pattern definition

central object or system with frequently changing data or message or it changes state (observable aka subject). multiple other objects on the other side that needs this new information (observers). observable has a 1..n relationship with observers. many different observers but then one central observable. how does the information go from the central objects to the multiple parties? or do the multiple parties come and ask frequently about the changing methods?

structural patterns

concerned with non-trivial relationships among classes.

To illustrate a behavioral design pattern

consider the problem of capturing the mutual, interacting behavior of a ship and a tugboat as the ship enters a port. We need a Ship and a Tugboat class but what should their relationship be? A good technique to avoid mutual dependency is to introduce a third party class that's aware of both elements, designed specially for the application. Notice that Ship and Tugboat are not aware of LeavingPort so their code is portable.

Example of abstract factory method

different components needed to make a specific style of pizza so therefore, that type of stuff should be created together and placed together so that the correct type is made

creational patterns

have to do with the process of creating ensembles of related classes. Abstract Factory is such an example.

bank account example

l Creating Bank accounts may include multiple bank internal sub- processes that we want to hide. l Bank front desk employees should not deal with all of the internal subprocesses, they should be able to simply create accounts for customers. l A front desk person just ask the customer which kind of bank accounts (checking or saving) accounts she/he wants to have and accounts can be easily created. l BankAccount bankAccount= AccountFactory.createAccount()

participants in this pattern

l Product - defines the interface of objects the factory method creates. ConcreteProduct - implements the Product interface. Creator - It declares the factory method, which returns an object of type Product. Creator may also define a default implementation of the factory method that returns a default ConcreteProduct object. - It may call the factory method to create a Product object. l ConcreteCreator - overrides the factory method to return an instance of a ConcreteProduct.

consequences of using factory pattern

l Provides hooks for subclasses. - Creating objects using factory method is more flexible than creating an object directly. - Factory Method gives subclasses a hook for providing an extended version of an object. l Connects parallel class hierarchies. - In our examples we've considered that the factory method is only called by Creators. But this doesn't have to be the case; clients can find factory methods useful, especially in the case of parallel class hierarchies.

abstract factory pattern summary

l The Factory Method pattern is one of the straightforward patterns. Abstract Factory l Abstract Factory classes are often implemented with factory methods (Factory Method), but they can also be implemented using Prototype Pattern (We will learn that later) . l We've certainly seen that Abstract Factory allows a client to use an abstract interface to create a set of related products without knowing about the concrete products that are actually produced.

summary of observer pattern

l The observer pattern defines a one-to-many push dependency relation between an observable and many observers so that when the observable has changes (state, events, etc.), all its dependents are notified and updated automatically. l Objects (observers and observable) are responsible for themselves l Observer class represent the concept of objects that needed to be notified about events and it provide a common interface for the subject to notify the observer objects.

when to use the factory method pattern

l Use Factory Method when - a class can't anticipate the class of objects it must create. - a class wants its subclasses to specify the objects it creates. - classes delegate responsibility to one of several helper subclasses, and you want to localize the knowledge of which helper subclass is the delegate.

problem for the observer pattern

l You need to notify a varying list of objects that an event has occurred. l How should we get other components updated considering the requirements and optimal costs? l Some of the important requirements: - Subject should know less about the subscribers. - We should be able add new observers at any time. - We should not need to modify the subject to add new types of observers. - Changes to either the subject object or an observer should not affect the other. We want to have Loosely coupled designs.

structure of strategy pattern

make car class simple. applyBrake() iterates through the collection of brakes and grabs the one that it needs. brake behavior is interface. when executing can decide how the brake can be executed. make seperate class bc its the only thing changed

Observer is used when ____ need to be notified when a ____ of an object changes.

objects, value

roles in using a design pattern

roles involved in actually using a design pattern. The main role is #3: the actual application of the design pattern. The client role represents the code that uses the design pattern application. The setup code needs to reference more or less every part, to put everything in place.

problem for abstract factory method:

same as factory, now consider creating multiple objects of different types. multiple objects created at same time, these have set of different objects u wanna create. and when u create that type, its of a particular set, set A or set B when u want to create, want to make sure youre getting (A1 and A2) together and call them type A. make sure they're is a consistency when you create the set objects. you would never get a mix of different types (ex: A1 and B2). This helps keep consistency of the application. families of objects of classes, have to be created togeher.

When a design pattern is used in an application, there are 3 roles. What are they?

setup, client, design pattern application

strategy pattern

sometimes in your software design there are similar objects that are only different in some behaviours. and at runtime, you want to switch bw those behaviors those behaviours are called strategies. ex: cars. some cars only different in how their brakes are implemented. some use Antilock brake system and some use traditional brakes. and at runtime you want to switch bw brake behaviors. in software: these would be different computations u wanna run on the data or switch bw diff web services you have and you want to dynamically change bw those behaviours.

What are the two aspects of using a design pattern, and how are they expressed?

static (the class model) and dynamic (typically expressed via sequence diagrams or state models).

The key method ____ is, possessed by every ____ needing notification.

update(), value

factory pattern

when u have a class heirarchy, and at some point you want to create objects. pass parameter to a method and that method can at runtime, decide which subclass to create. tell the factory how to generate one of the objects

polymorphic encapsulation

• Subject does not to know what kind of observer it is communicating with. If we have a new observer, no change is need to be done on Subject side. This kind of interaction in observer pattern is also known as publish-subscribe (Pub/Sub). Publish-Subscribe system is a topic in distributed event-based systems.

When to use strategy pattern:

• You have many related classes differ only in their behavior.• You have different variants of an algorithm or functionality • You want to avoid exposing complex, algorithm-specific data structures to clients. An algorithm uses data that you want to hide it from client. • You have a class that defines many behaviors and these have multiple conditional statements in its operations.


Kaugnay na mga set ng pag-aaral

MEDSURG TEST #2: CH 43 - Liver Cancer/Transplant, Pancreas and Gallbladder Problems

View Set

Mathematical Operators and Code Practice

View Set

Patho Wk 7 Ch (36, 37, 38, 40, 41) Song WCU, WEEK 7 PATHO 370, Week 7 Patho WCU, Patho Week 7 Quiz, WCU Patho Week 7 - Ch. 36, 37, 38, 41

View Set

Chapter 46: Antineoplastic Drugs Part 2

View Set