Top Banner
Advanced Software Engineering University of Colombo Prabha Kularathna
54

Advanced Software Engineering Lecture 03

Nov 03, 2015

Download

Documents

Buddhika Gamage

se
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript

Advanced Software Engineering

Advanced Software EngineeringUniversity of ColomboPrabha KularathnaSoftware Design2TypeDescriptionExamplesIdiomsSpecific to a particular language, system or toolScoped locking,Lambda expressionsDesign PatternsCaptures recurring patterns at programming level and common solutions applicable.Singleton,Strategy,Proxy,ObserverArchitectural PatternsCaptures recurring patterns at architectural levelLayers, Publisher-subscriber, MVC, Unit-of-workOptimization Principle PatternsDocumented rules for avoiding common design / implementation mistakes that effect performanceCaching,Optimizing for common case, Passing information between layersPatterns in software a taxonomyDesign Patterns4DefinitionDesign PatternsIn software engineering, a design pattern is a general reusable solution to a commonly occurring problem within a given context in software design. A design pattern is not a finished design that can be transformed directly into source or machine code. It is a description or template for how to solve a problem that can be used in many different situations.Design patterns reference:design patterns: elements of reusable object-oriented software5Why?Design PatternsAvoid re-inventing the wheel Save time / costYour wheel is mostly sub-optimal!Easy to communicate in designing / discussionsA must have for todays programming

6Design Patterns

7Gang-of-FourDesign Patterns

8Creational PatternsAbstract FactoryCreates an instance of several families of classesBuilderSeparates object construction from its representationFactory MethodCreates an instance of several derived classesPrototypeA fully initialized instance to be copied or clonedSingletonA class of which only a single instance can existStructural PatternsAdapterMatch interfaces of different classesBridgeSeparates an objects interface from its implementationCompositeA tree structure of simple and composite objectsDecoratorAdd responsibilities to objects dynamicallyFacadeA single class that represents an entire subsystemFlyweightA fine-grained instance used for efficient sharingProxyAn object representing another object

Behavioral PatternsChain of ResponsibilityA way of passing a request between a chain of objectsCommandEncapsulate a command request as an objectInterpreterA way to include language elements in a programIteratorSequentially access the elements of a collectionMediatorDefines simplified communication between classesMementoCapture and restore an object's internal stateObserverA way of notifying change to a number of classesStateAlter an object's behavior when its state changesStrategyEncapsulates an algorithm inside a classTemplate MethodDefer the exact steps of an algorithm to a subclassVisitorDefines a new operation to a class without changeSingletonCreational PatternsUsed to make sure theres only one instance of a class exists at any given time in the runtime.

11SingletonCreational PatternsMay provide a global point of access to a limited resource.Ex: a cache of objectsMay represent a single resource that is logically singularEx: a class that represents underlying application12SingletonCreational PatternsCan be easily achieved by having a global static variable that is initialized at declaration, but this is risky as:

Can add startup overhead since lazy loading is not usedCan lead to having multiple copies for multiple threads which is not intentional, causing almost-impossible to detect bugs

You can have thread specific singletons.13SingletonCreational Patterns public sealed class Singleton { private static Singleton instance; private static object lock_ = new object();

private Singleton() { }

public static Singleton GetSingleton() { lock (lock_) { if (instance == null) instance = new Singleton(); }

return instance; } }14PrototypeCreational PatternsProvides a way to create a new object using the current object as a prototype

15PrototypeCreational PatternsIf the object is very simple, creating a prototype of itself is trivial.4th generation object oriented programming languages (ex: Java, C#) readily provide some useful constructs for prototype design pattern.

Cloning types:Shallow clone: clone only the immediate members of given objectDeep clone: clone each member of given object, effectively copying each member object of the object graph.16Factory MethodCreational PatternsProvides a factory class with a method which can return a specific concrete type of an object for given situation.

This provides a single point of access to create an object out of a set of concrete implementations of an abstract class, which effectively enhances readability & discoverability.17Factory MethodCreational Patterns

18Factory MethodCreational Patterns public abstract class ProductBase { }

public class ConcreteProduct1 : ProductBase { }

public class ConcreteProduct2 : ProductBase { }

public enum ProductTypes { Product1, Product2 }19Factory MethodCreational Patterns public abstract class FactoryBase { public abstract ProductBase FactoryMethod(ProductTypes type); }

public class ConcreteFactory : FactoryBase { public override ProductBase FactoryMethod(ProductTypes type) { switch (type) { case ProductTypes.Product1: return new ConcreteProduct1();

case ProductTypes.Product2: return new ConcreteProduct2();

default: throw new ArgumentException("Unsupported type.", "type"); } } }20Abstract FactoryCreational PatternsA Factory object typically acts as a factory to create a set of requested objects. Abstract Factory design pattern provides means to have different factory implementations for different situations, were each factory is capable of creating the requested object for the given situation. 21Abstract FactoryCreational Patterns

22Abstract FactoryCreational Patterns public abstract class AbstractProductA { }

public class ProductA1 : AbstractProductA { }

public class ProductA2 : AbstractProductA { }

public abstract class AbstractProductB { }

public class ProductB1 : AbstractProductB { }

public class ProductB2 : AbstractProductB { }

public abstract class AbstractFactory { public abstract AbstractProductA CreateProductA();

public abstract AbstractProductB CreateProductB(); }

23Abstract FactoryCreational Patterns public class ConcreteFactoryA : AbstractFactory { public override AbstractProductA CreateProductA() { return new ProductA1(); }

public override AbstractProductB CreateProductB() { return new ProductB1(); } }24Abstract FactoryCreational Patterns public class ConcreteFactoryB : AbstractFactory { public override AbstractProductA CreateProductA() { return new ProductA2(); }

public override AbstractProductB CreateProductB() { return new ProductB2(); } }25AdapterStructural PatternsAllows two incompatible types to communicate

26AdapterStructural Patterns public interface ITarget { void MethodA(); }

public class Adaptee { public void MethodB() { Console.WriteLine("MethodB called"); } }

public class Adapter : ITarget { Adaptee adaptee = new Adaptee();

public void MethodA() { adaptee.MethodB(); } }

27AdapterStructural Patterns public class Client { private ITarget target;

public Client(ITarget target) { this.target = target; }

public void MakeRequest() { target.MethodA(); } }28CompositeStructural PatternsThe composite pattern describes that a group of objects is to be treated in the same way as a single instance of an object. The intent of a composite is to "compose" objects into tree structures to represent part-whole hierarchies. Implementing the composite pattern lets clients treat individual objects and compositions uniformly29CompositeStructural Patterns

30CompositeStructural Patterns public class Circle { private int x, y, radius;

private Circle[] children;

//...

public void Move(int dx, int dy) { this.x += dx; this.y += dy;

foreach(Circle child in children) { child.Move(dx, dy); } } }31DecoratorStructural Patternsextends the functionality of individual objects by wrapping them with one or more decorator classes. These decorators can modify existing members and add new methods and properties at run-time.32DecoratorStructural Patterns

33DecoratorStructural Patterns using (FileStream fs = new FileStream("C:\\MyFile.txt")) { using(BufferedStream bs = new BufferedStream(fs)) { using(StreamReader r = new StreamReader(bs)) { return r.ReadToEnd(); } } }34Behavioral PatternsCommandEncapsulates a request, with its parameters so that it can be decoupled from the place of origin

35Behavioral PatternsCommand public interface ICommand { void Execute(); }

public class CopyCommand : ICommand { public void Execute() { // get text from currently focused text field & move it to clipboard } }

public class PasteCommand : ICommand { public void Execute() { // if clipboard has text, paste it into currently focused text field } }36Behavioral PatternsIteratorDefines a standard interface to iterate through a collection of objects, without needing to understand the underlying structure of these objects.

37Behavioral PatternsIteratorModern object oriented programming languages (Ex: Java / C#) readily follow this pattern in their collection implementations

Ex: Java: all collection classes implementing java.util.Iterator interface.C#: all collection classes implementing System.Collections.IEnumerator interface.38Behavioral PatternsObserverEnables a means to observe the state of an object, so that whenever the state of the object changes, all objects observing this object will be informed. This pattern allows communication between objects in a loosely coupled manner.

39Behavioral PatternsObserverThis allows objects to simply register to observe a change in an object, so when this change is happened, all registered objects are informed by invoking a designated method.

For example, event handling in Java is done purely based on observer design pattern.40Behavioral PatternsObserver @Overridepublic boolean onCreateOptionsMenu(Menu menu) {Button button = (Button) findViewById(R.id.button1);

button.setOnClickListener(new OnClickListener() {

@Overridepublic void onClick(View view) {Toast.makeText(MainActivity.this, "Button Clicked", Toast.LENGTH_SHORT).show();}

});return true;}This time, an example from Android!41Behavioral PatternsStrategyAllows to use a different algorithm (strategy) based on the current situation.

42Behavioral PatternsStrategy public abstract class PaymentStrategy { public abstract void Pay(decimal amount); }

public class CreditCardPaymentStrategy : PaymentStrategy { public override void Pay(decimal amount) { // pay via connecting VISA / MASTERCARD banking services. } }

public class PayPalPaymentStrategy : PaymentStrategy { public override void Pay(decimal amount) { // pay via PayPal service. } }43Behavioral PatternsStrategy public class ShoppingCart { //...

public void Checkout(PaymentStrategy paymentStrategy) { decimal amount = CalculateTotal(); paymentStrategy.Pay(amount); }

}44Design PatternsSource: www.google.comThere are many new design patterns other than GOFhttp://www.oodesign.com/Architectural Patterns46Architectural PatternsLayersDesigning systems architecture as a stack of layers whereEach lower layer exposes it to the layer above (and optionally, to the outside world) via a well-defined protocol.Each upper layer provides a relatively higher-level of abstraction in terms of functionality, using the lower layer. Lower layers protocol is used to communicate with it.An upper layer depends on / uses functionality of the lower layer. Not the other way around.Layer Layer 2Layer 1Layer NEach layer may expose its functionality to outside world in the defined protocolHigh level, coarse-grained functionalityLow level, fine-grained functionality47Architectural PatternsLayers

Java Standard Edition librarieshttp://www.oracle.com/technetwork/java/javase/tech/index.html48Architectural PatternsLayers

Bluethoth Smart protocol stackhttps://developer.bluetooth.org/TechnologyOverview/Pages/BLE.aspx 49FaadeArchitectural PatternsProvides a simple, unified interface to a complex subsystem

50Architectural PatternsModel-View-Controller (MVC)Heavily used when designing interactive application architectures.Some development platforms are inherently MVCASP.NET MVCiOS applications

51Architectural PatternsModel-View-Controller (MVC)

Displays the GUIand captures user actions.Maintains the data model associated with the view. For a large application, typically connected with a persistence storage (ex: database / cloud / web server).Observes user actions.Makes changes in data model / persistence storage andupdates View accordingly.52Architectural PatternsService LocatorProvides decoupling between functionality and its consumer, where the actual implementation of the functionality is not needed to be available at design / compile time.Also known as Dependency Injection, or Inversion of Control

53Architectural PatternsService LocatorSome consider this as an anti-pattern

Anti-pattern

An AntiPattern is a pattern that tells how to go from a problem to a bad solution. (Contrast to an AmeliorationPattern, which is a pattern that tells how to go from a bad solution to a good solution.)

An anti-pattern is something that looks like a good idea, but which backfires badly when applied.

http://c2.com/cgi/wiki?AntiPattern54