advanced software engineeringharoldliu.weebly.com/uploads/1/5/8/1/15810196/sw_design...data...

Post on 29-Jul-2020

0 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

Advanced Software Engineering

Lecture 3: Software Designs

Prof. Harold Liu

Outline What is software architecture? Typical software architectural styles Specific software architectures Distributed system architectures Software architecture patterns Design patterns UI designs

1 What is Software Architecture? Clements, Paul; Felix Bachmann, Len Bass, David Garlan, James 

Ivers, Reed Little, Paulo Merson, Robert Nord, Judith Stafford (2010). Documenting Software Architectures: Views and Beyond, Second Edition. Boston: Addison‐Wesley. ISBN 0‐321‐55268‐7.  

“the high level structures of a software system. It can be defined as the set of structures needed to reason about the software system, which comprise the software elements, the relations between them, and the properties of both elements and relations”

This definition emphasizes the important role of “software elements”

1.Pattern The elements of this language are entities called patterns. 

Each pattern describes a problem that occurs over and over again in our environment, and then describes 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. — Christopher Alexander 

Architectural pattern: a standard solution to architectural problems in software engineering ("strictly described and commonly available"), e.g.: OSI reference model

Design pattern: a standard solution to common problems in software design

Gang of Four – 23 design patterns

Software Pattern, Style and Framework

2.Software Style "An architectural style defines: a family of systems in terms of a 

pattern of structural organization; a vocabulary of components and connectors, with constraints on how they can be combined 

The main difference is that a pattern can be seen as a solution to a problem, while a style is more general and does not require a problem to solve for its appearance.:

3.Software Framework a software framework is an abstraction in which software 

providing generic functionality can be selectively changed by additional user‐written code, thus providing application‐specific software. 

A software framework is a universal, reusable software platform to develop applications, products and solutions. 

Software frameworks include support programs, compilers, code libraries, tool sets, and APIs that bring together all the different components to enable development of a project or solution.

Typical examples include MVC and Struts

The input data go through a series of calculations and operations and evetually form the output data

Examples: Pipe/filter, batch sequential processing

Data flow

2. Typical Software Styles

Call‐Return1.Main program/subroutine

divide the functionality into a control tree

2.Layered architecture each layer provides a set of services 

to the layers above encapsulates a set of 

implementations and lower‐level services

relies on services from the layers below

Reference Model

Designed for specific application domains; an ideal software architecturethat include all necessary features

Warehouse

Hypertext, database, blackboard system Data warehouse situates at the centre of the architecture, othercomponents interact with it for CRUD

4 Distributed System Architectures Centralized computing era highly rely on the mainframes and high‐

end servers

After 1980s, personal computer becomes available that eventually help generate the distributed computing model

Characteristics Disadvantages

Simplest distributed system model. System composed of multiple processes which may (but need not) execute on different processors.

Architectural model of many large real‐time systems. Distribution of process to processor may be pre‐ordered or may be under the control of a dispatcher.

Multiprocessor Architecture

The application is modeled as a set of services that are provided by servers and a set of clients that use these services.

Clients know of servers but servers need not know of clients.

Clients and servers are logical processes The mapping of processors to processes is not necessarily 

1:1.

Client/Server (C/S)

Thin Client

Fat Client

Example: Internet Banking

Summary of C/S Architecture

Distributed Object Architectures

Advantages

Example: data mining systems

model‐view‐controller, that separate user inputs, data model and data representations

5 Architectural Frameworks MVC

6. Design Patterns

What is design pattern?

Creational

Structural

Behavioral

To solve a category of software problems and make it reusable

In the class and object level

More in the high‐level design stage 

Key idea is to add the abstraction layer, to separate the variants from the invariants

What is Design Pattern?

Pattern Name: we use to describe a design problem,

Problem: that describes when to apply the pattern, the causal relationship of the problem and potential preconditions that have to be satisfied in order to use the pattern

Solution: that describes the elements that make up the design

Consequences: that are the results and trade‐offs of applying the pattern.

Basic Elements of A Pattern

SOLID Principles

"software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification“

such an entity can allow its behavior to be modified without altering its source code. 

This is especially valuable in a production environment, where changes to source code may necessitate code reviews, unit tests, and other such procedures to qualify it for use in a product: code obeying the principle doesn't change when it is extended, and therefore needs no such effort. 

Inheritance

Open/Closed Principle

• every class should have a single responsibility, and that responsibility should be entirely encapsulated by the class. All its services should be narrowly aligned with that responsibility. 

• The reason it is important to keep a class focused on a single concern is that it makes the class more robust 

• Example:• interface Modem{• public void dial(String pno);• public void hangup();• public send(char c);• public char recv();• } • Modem class has 2 responsibilities: connection and communications, 

should be separated

SRP

LSP

Substitutability states that, if S is a subtype of T, then objects of type T may be replaced with objects of type S (i.e., objects of type S may be substituted for objects of type T) without altering any of the desirable properties of that program (correctness, task performed, etc.).  LSP is a particular definition of a subtyping relation, called (strong) behavioral subtyping   Example: is penguin a bird? 

Biological: yes, it is.LSP: no, it is not, since it cannot fly.

DIP

High‐level modules should not depend on low‐level modules. Both should depend on abstractions.

Abstractions should not depend upon details. Details should depend upon abstractions.

ISP

No client should be forced to depend on methods it does 

not use.

ISP splits interfaces which are very large into smaller and 

more specific ones so that clients will only have to know 

about the methods that are of interest to them. 

Such shrunken interfaces are also called role interfaces.

ISP is intended to keep a system decoupled and thus 

easier to refactor, change, and redeploy. 

ISP Example

Singleton Method

Factory Method

Abstract Factory Method

Builder Method

Prototype Method

Creational Design Patterns

CompositeDecoratorProxyFlyweight FaçadeBridgeAdapter

Structural Design Patterns

TemplateObserver IteratorChain of ResponsibilityMementoCommandStateVisitor InterpreterMediatorStrategy

Behavioral Design Patterns

Singleton

The system only allows ONE window, ONE file system

A digital filter can have only ONE A/D converter

A accounting system can be used only in ONE company

Singleton: Structure

Define an Instance method, allow clients to access its unique instance

public class Car{ public void run(){System.out.prinln(“…”)}; }

public class Test{ public static void main(String[] args) Car c= new Car(); c.run(); }

Example to make a car to run…

public class Car{ private Car(){} public static Car getInstance(){return new Car()}; public void run(){System.out.prinln(“…”)}; }

public class Test{ public static void main(String[] args) Car c= Car.getInstance(); c.run(); }

An improvement

public class Car{ private static Car car=new Car(); private Car(){} public static Car getInstance(){return car;} public void run(){System.out.prinln(“…”)}; }

public class Test{ public static void main(String[] args) Car c1= Car.getInstance(); Car c2= Car.getInstance()’ if(c1==c2) System.out.println(“…”); c.run(); }

Finally…

An Extension: Multiton  Public class Test{ public static void main(String[] args) Car c1= Car.getInstance(); Car c2= Car.getInstance()’ if(c1==c2) System.out.println(); c.run(); }

Public class Car{ private static Car car=new Car();

private static List<Car> cars=new ArrayList<Car>(); private Car(){ public static Car getInstance(){return car;} } public void run(){System.out.prinln(“”)}; }

Factory Method

NEW an object: we have to know the exact class information of that object, but sometimes impossible, e.g., to watch a video needs to open up an player, but clients don’t know which player, as the job of the system to assign 

to implement the concept of factories and deals with the problem of creating objects (products) without specifying the exact class of object that will be created. 

The essence of this pattern is to "Define an interface for creating an object, but let the classes that implement the interface decide which class to instantiate. 

The Factory method lets a class defer instantiation to subclasses.

Structure

Product: define fun() to create object (product)

ConcreteProduct: implement product interface fun()

Factory: declare CreateProduct() return an object with Product class

FileLog

EventLog

Example: Log Manager

// LogFactory classpublic abstract class LogFactory{public abstract Log Create();

}

// FileFactorypublic class FileFactory:LogFactory{public override FileLog Create(){

return new FileLog();}

}

// EventFactorypublic class EventFactory:LogFactory{public override EventLog Create(){

return new EventLog();}

}

public class App{public static void Main(string[] args){LogFactory factory = new EventFactory();

Log log = factory.Create();

log.Write();}

}

Public interface Moveable{ public void run(); }

Public class Plane implements Moveable{ @Override public void run(){…};}

Public class Car implements Moveable{ @Override public void run(){…};}

Public abstract class VehicleFactory{abstract Moveable create();} Public class PlaneFactory extends VehicleFactory{public Moveable

create(){return new Plane();} } Public class CarFactory extends VehicleFactory{public Moveable create(){return

new Car();} }

Public class Test{ public static void main(String[] args){ VehicleFactory f=new PlaneFactory(); // the only change happens here! Moveable m= factory.create(); m.run();} }

Example: customize vehicle types and its production

Abstract Factory Method provides a way to 

encapsulate a group of individual factories that have a common theme without specifying their concrete classes.

change windows theme, 

then buttons, tasks, 

menus, tools, all changed 

accordingly.

Structure

Abstract Factory: declare the interface to create abstract product

ConcreteFactory: implements CreateProduct()

Abstract Product: declare ONE interface for a group of product

ConcreteProduct: define how to create a product by a factory

Example: a series of product replacement public class Car extends Vehicle{} public class AK47 extends Weapon{} public class Apple extends Food{public Void printName(return…);}

public abstract class Vehicle{public abstract void run();} public abstract class Weapon{public abstract void shoot();} public abstract class Food{public abstract void printName();}

public abstract class AbstractFactory{ public abstract Vehicle createVehicle(); public abstract Weapon createWeapon(); public abstract Food createFood(); }

public class DefaultFactory extends AbstractFactory{ public Vehicle createVehicle(){return new Car();} public Weapon createWeapon(){return new AK47();}; public Food createFood(){return new Apple();}; }

public class MagicFactory extends AbstractFactory{ public Vehicle createVehicle(){return new Broom();} public Weapon createWeapon(){return new MagicStick();}; public Food createFood(){return new Mushroom();}; }

public class Test{

AbstactFactory f=new DefaultFactory();// only changes here to MagicFactory(); Vehicle v=f.createVehicle();c.run(); Weapon w=f.createWeapon();w.shoot(); Food a = f.createFood();a.printName(); }

Three styles: elegant, practical and lazy

Three positions to place plants: flower bed, corner and 

garden center

Example: Design a Garden

style/position Flower bed corner Garden center

elegant tulips Banyan Bluegrass

Practical Grapes Pomegranate Loofah

Lazy Rose Camellia bamboo

Difference between Factory Method and Abstract Factory Method

Builder Pattern

Director: construct an object to use the Builder interface

Builder: declare an abstract interface to construct a Product

ConcreteBuilder: implement Builder interface to construct the product

Product: the complex object to be constructed

Structure

Difference from Abstract Factory

Builder focuses on constructing a complex object step by step. 

Abstract Factory emphasizes a family of product objects (either simple or complex). 

Abstract Factory is for a family of related products. The Builder is for one product.

If you have a new office, and only need new desks, you would use a Builder. A desk will always be a desk, but there are many different configurations for a desk, i.e., size, shape, presence of a hutch, drawers, etc.

If you have a new office, and the inside is completely bare, you would need various objects and would use an Abstract Factory that creates Furniture, from which our Desk descends. In this case, Desk as we know is a "complex" object, so it uses the Builder pattern, but here it is part of a directing Abstract Factory. The Abstract Factory would also create simple objects, like very specific lamps (StraightFunkyLamp), via a StraightFunkyLampFactory class.

a house is composed of 5 parts

Floors

walls

windows

doors

ceilings

Construction steps are fixed, but concrete components (doors, windows) will change

use Builder pattern to separate the variants (doors, windows) from the invariants (construction process)

Example: Build a house in a computer game

public abstract class House //abstract House class{ }

public abstract class Builder //variables{public abstract void BuildFloor();public abstract void BuildDoor();public abstract void BuildWindows();public abstract void BuildWall();public abstract void BuildHouseCeiling()

public abstract House GetHouse();}

public abstract class GameManager{public static House CreateHouse(Builder builder){builder.BuildFloor();builder.BuildDoor();builder.Buildwall();builder.BuildWindows();builder.BuildHouseCeiling();

return builder.GetHouse();}

}

public class RomanHouseBuilder : Builder{public override void BuildDoor()   { }public override void BuildFloor()  { }public override void BuildWindows()   { }public override void BuildWall()   { }public override void BuildHouseCeiling()   { }public override House GetHouse()  { }

}

class App{public static void main(){House house =GameManager.CreateHouse(new 

RomanHouseBuilder());}

}

Example: Vehicle manufacturing

Prototype PatternWhen a client wants to create an object (product):

‐ Knows exactly which type (class), then use NEW‐ Only knows specific requirements, then use FACTORY method‐ Only knows that a similar object is needed, then use PROTOTYPE

Structure

Client: send object creation request to prototype manager

Prototype: an abstract interface 

ConcretePrototype: cloned object

PrototypeManager: create concrete product

Palette: click any of the color return an instance of that color

Treat each color as an object, abstract to a super class

Example 1: Palette

Singleton: ensure there is only one instance and provide 

global access point

Factory: define an interface to create object, and let the 

subclass to decide how to instantiate the concrete product

Abstract factory: define an interface, to create a family of 

product

Builder: encapsulate the construction steps of a product

Prototype: to copy/clone from an existing object

Summary of Creational Design Patterns

Composite Pattern

Decorator Pattern

Proxy Pattern

Flyweight Pattern

Façade Pattern

Bridge Pattern

Adapter Pattern

Structural Design Patterns

Adaptor Pattern Case: a team provides S service, but it does not have capable 

team members

Only A outside the team can do the job.

To recruit A into the team

A does not want to join the team, arrange B to finish the job while let A teach B how to do it.

Now, B is a composite entity (providing service, inherited/learn from A)

Convert an interface from a class to another expected interface

Adaptor pattern allows two classes without compatible interface to work together

How to use it?

Client initializes the request through targeted interface 

method

Adaptor uses the Adaptee’s interface to convert the request 

to the desired interface

Client receives the result, however does not how what 

happened at all.

Aim and Feasibility

Aim: to convert an interface to the user desired another interface, so that to allow two separate interfaces can seamlessly work together

Where to use:

To use an existing class, but its interface is not usable

Create a reusable class that it can work with other class (potentially with different interfaces

To use existing subclasses, but cannot match their interfaces through inheritance. Object adaptor is then used to adapt its superclass interface

Two types: Class Adaptor and Object Adaptor

Structure

Use a specific Adapter class to match the Adaptee and Target classes.

Adapter class multi‐inherits from Adaptee and Target classes Adapter can overwrite Adaptee’s methods, since Adapter 

implements it

Example:

//Target: define the interface (and method) that Client will use public interface Target {  void request();  }

//Adaptee: the existing interface public class Adaptee {  public void specificRequest(){} }

//Adapter: extends Adaptee and implement Target interface public class Adapter extends Adaptee implements Target { public void request() {

super. specificRequest();}

}

Object Adaptor

Allow one Adapter to talk with multiple Adaptees Adaptee itself and all inherited subclasses can work together Adapter can add method to all Adaptees

Example: Object Adaptor//Target: define the interface that client will use public interface Target {  void request();  }

//Adaptee: the existing interface public class Adaptee {  public void specificRequest(){} }

//Adapter: to match the Adaptee’s interface with Target’s interface public class Adapter implements Target { public Adapter(Adaptee adaptee) { super(); this.adaptee = adaptee; } public void request(){ adaptee.specificRequest(); } private Adaptee adaptee; 

}

Pros and Cons

Pros:

Very convenient for designers to freely design interfaces, 

don’t need to worry about the adaptability

Cons

Static structure. Since only single inheritance is allowed, 

cannot use in the case where multiple Adaptees want to talk 

with a single Target

Template method Pattern Observer Pattern Iterator Pattern Chain of Responsibility Pattern  Memento Pattern  Command Pattern State Pattern  Visitor Pattern Mediator Pattern  Strategy Pattern Interpreter Pattern

Behavior Patterns

Strategy PatternMany algorithms may realize ONE functionality. Clients want to 

choose one of them under different contexts Difficult to maintain the class using an algorithm: especially 

many algos need to be supported, and each is very complex To choose an algo upon different conditions; to support an algo 

that will not be used will cause performance problem Tightly coupling between the algo implementation and the class 

using it, so very challenging to add one more algo

Solution: to separate the algo from the class using it and become an independent algo object, then to abstract the common feature as the interface, finally the class uses the composite algo interfaces

Aim and Feasibility

Aim: to define a series of algos, encapsulate each, so that it is independent with the client’s change

Where to use it? Software construction stage: some object many use 

many methods, and frequently change, if hard code all these algos into the object implementations, it will become very complex, and sometimes an algo may not be used in the future

Question: how to transparently change an object’s method? How to decouple the method and object itself?

Structure:

Participants

Strategy Define the common interface to be used by all strategies Context uses this interface to call a specific ConcreteStrategy

ConcreteStrategy Implement the Strategy interface

Consequence AnalysisPros: Separate the algo and the class using it; client can select an 

algo at runtime, reusable code, easy to revise and maintain Use composition to replace inheritance: if to inherit a subclass 

directly from Context class, may also help, but this inheritance makes tight coupling between subclass and super class

Strategy pattern uses composition, de‐coupling the Context class the implemented Strategies

Compare with switch conditions, not hard code into a class Client can choose different algos from different context at 

runtime

Cons: Client needs to know exactly what functionality each algo can 

provide Communication cost between algos and Context: Context 

needs to pass different parameters to each algo class, thus Context class may create and pass some parameters never used by some algos

Increase the no. of class and objects: each algo becomes a class, thus challenging to maintain when large no. of algos exist

Separate the variants from invariants

Implement DUCK’s behaviors

Another Example: Diff Sort Algos Below is how strategy pattern helps encapsulate different sort algorithms for different objects, allowing clients to dynamically change respective algorithm

e.g., Quicksort, Shellsort, Mergesort

Example: Book Discount Some books have no discount Some books only have a flat rate discount $1 Some books have an x% discount

top related