design example n.
Download
Skip this Video
Loading SlideShow in 5 Seconds..
Design example PowerPoint Presentation
Download Presentation
Design example

Loading in 2 Seconds...

play fullscreen
1 / 60

Design example - PowerPoint PPT Presentation


  • 107 Views
  • Uploaded on

Design example. GUI (Graphical User Interface) toolkit A typical GUI has many different objects Menu, window, button, scrollbar, . . . Hierarchical structure Objects within an object e.g. Window within a window, button within a button OO provides a simple solution to these problems.

loader
I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.
capcha
Download Presentation

PowerPoint Slideshow about 'Design example' - nayef


An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript
design example
Design example
  • GUI (Graphical User Interface) toolkit
    • A typical GUI has many different objects
      • Menu, window, button, scrollbar, . . .
    • Hierarchical structure
      • Objects within an object
      • e.g. Window within a window, button within a button
    • OO provides a simple solution to these problems
how to draw gui objects
How to draw GUI objects?
  • Put all concrete objects into a Glyph container; ask each Glyph to draw itself

Glyph container

Glyph

(System provided)

Draw()

Glyph

Draw()

Add

Glyph

Draw()

Concrete Glyph

(user provided)

Draw()

Glyph

Draw()

Glyph

Draw()

how to draw gui objects1
How to draw GUI objects?
  • Glyph[] window = {new Button(),

new ScrollBar()};

foreach (g in Window) g.Draw();

Glyph

virtual void Draw()

Button

void Draw()

ScrollBar

void Draw()

Panel

void Draw()

upcasting and polymorphism
Upcasting and polymorphism
  • Create concrete objects
    • new Button(),new ScrollBar()};
  • Add to an abstract container
    • Container only knows abstract base class Glyph
  • Upcasting
    • Button is upcasted to Glyph
  • Polymorphism
    • All concrete objects are treated uniformly (same) as Glyph
    • foreach (g in Window) g.Draw();
composition
Composition
  • Is Window a kind of glyph?
  • Yes, window shares many common properties with buttons, scroll bars, panel, . . .
    • Is-a relationship = inheritance

Glyph

is-a

Window

Button

ScrollBar

Panel

composition1
Composition
  • But Window can have some buttons, scroll bars, etc.
    • Has-a relationship = composition
    • Window has a number of glyphs

has-a

Window

Glyph

is-a

Button

ScrollBar

Panel

is a and has a relationships
Is-a

Inheritance

Window is-a Glyph

class Window : Glyph

{

. . .

}

Has-a

Composition

Window has-a few buttons, windows

class Window {

Glyph[] g;

. . .

}

Is-a and Has-a relationships
composition pattern
Composition pattern
  • Combining is-a and has-a
    • class Window : Glyph { //inheritance

Glyph[] g; //composition

. . .

}

  • So that we can have a window inside a window …

Glyph

is-a

has-a

Button

ScrollBar

Panel

Window

an even more general form of composition pattern
An even more general form of composition pattern
  • Can support any complex structure imaginable
    • e.g. a Window inside a Button
  • Glyph has-a Glyph container
    • class Glyph {

Glyph[] g;

. . .

}

has-a

Glyph

*

is-a

Button

ScrollBar

Panel

Window

an even more general form of composition pattern1
An even more general form of composition pattern
  • class Window : Glyph {

. . .

}

  • Window inherits the Glyph container from Glyph
    • Support Window inside a Button

has-a

Glyph

*

is-a

Button

ScrollBar

Panel

Window

limitation of inheritance
Limitation of inheritance
  • How to draw a different Button?

Glyph container

Glyph

(System provided)

Draw()

Glyph

Draw()

Add

Glyph

Draw()

Concrete Glyph

(user provided)

Draw()

Glyph

Draw()

Glyph

Draw()

limitation of inheritance1
Limitation of inheritance
  • Base class’s Draw() is overrided by the subclass
  • The actual Draw() is done by the concrete subclass
  • To draw a different look-and-feel button?
    • Can’t change Draw() at run-time unless you replace the concrete object in the container by a new object with a different Draw()
    • tedious
delegation
Delegation
  • To outsource the drawing action to a drawing object
    • So that we can change the look-and-feel by changing the drawing object at run-time

Glyph container

Glyph

Draw(){

Obj.Draw()

}

Glyph

Draw()

Add

DrawingClass

Draw()

Glyph

Draw()

Glyph

Draw()

the essential ideas of oo
The essential ideas of OO
  • INHERITANCE (is-a)
    • Similar types of objects that share the same interface
  • COMPOSITION (has-a)
    • An object that is made up from other objects
  • DELEGATION
    • To outsource work to another object
    • Delegation has the same syntax as composition
design of callback
Design of Callback
  • What is callback?
    • The mechanism that allows an object to send message to another object
    • e.g. a mouse button is clicked, how to send this mouse-up event message to the mouse-up handler?
  • Window Server
    • Has a container that contains several GUI objects (Button, TextBox, ScrollBar, …)
    • If mouse is clicked, window server finds the clicked object in its container, and calls the object’s OnClick() virtual function
    • You provide the implementation of OnClick()
callback by inheritance
Callback by inheritance
  • Build the MyWindow object
  • Override OnClick()
  • Add the concrete MyWindow object to container as Form (polymorphism)

Window Server

Container

Form

virtual OnClick()

Form

virtual OnClick()

Form

virtual OnClick()

MyWindow

override OnClick()

get callback by inheritance
Get callback by inheritance

using System;

using System.Windows.Forms;

class MyWindow : Form {

static void Main() {

Application.Run(new MyWindow());

//start a window and wait for input event

}

protected override void OnClick(EventArgs e) {

Console.WriteLine(“I(the Form) am clicked”);

base.OnClick(e); //forward call to base

} //in case there are more things to do

}

callback by delegation
Callback by delegation
  • Encapsulate a function pointer into an object of type EventHandler
  • Add the EventHandler object to Form

Window server

Container

obj

Handler()

EventHandler

obj.Handler()

Form

Function pointer

callback by delegation1
Callback by delegation

class MyWindow : Form {

static void Main() {

Application.Run(new MyWindow());

}

public MyWindow() {

this.MouseUp += new EventHandler(this.Handler());

} //MouseUp is a container

private void Handler(object sender,System.EventArgs e){

Console.WriteLine(“call from {0}”,sender.ToString());

}

}

object

function pointer

Handler function

differences between the two approaches
Differences between the two approaches
  • Callback by inheritance is easier to understand
    • The mechanism is more direct and simple
  • Callback by delegation is more powerful
    • Can callback to multiple handlers (multicasting) by adding several EventHandler objects to the MouseUp container in Form
    • Can change the callback handler at run-time by changing the EventHandler object
delegate how to build your own handler object
Delegate – how toBuild your own handler object
  • delegate keyword
    • A built-in C# keyword that helps you to create your own EventHandler object easily
  • public delegate void MyHandler(Student s);
    • This instruction generates a class MyHandler
    • Can encapsulate any function pointer with a matched signature (void and Student)
example of using delegate to generate handler
Example of using delegate to generate handler

public delegate void CallbackDelegate(String s);

//a Callback class is generated automatically

Main() {

ArrayList list = new ArrayList();

Client c = new Client();

list.Add(new Callback(c.Notify());

foreach ( (Callback) obj in list)

obj(“server”);

}

Class Client {

private void Notify(String s) {

Console.WriteLine(“call from {0}”,s);

}

}

visual studio window forms
Visual Studio – Window Forms
  • Tool that helps you to design a GUI easily
    • Open a new project and choose Window Forms
    • Drag and drop GUI into the Form
add a button
Add a Button
  • In ToolBox window, drag a Button object and drop it to the position you want in the Form
change button s properties
Change Button’s properties
  • Can resize and move the button, and use the Properties window of the button to change the name.
the generated code view by right click on the form
The generated code (view by right click on the form)

public class Form1 : System.Windows.Forms.Form {

private System.Windows.Forms.Button button1;

static void Main() {

Application.Run(new Form1());

}

public Form1() {

InitializeComponent();

}

private void InitializeComponent() {

this.button1 = new System.Windows.Forms.Button();

//. . .

}

protected override void Dispose( bool disposing ) {

//. . .

}

}

notes
Notes
  • Application.Run(new Form1());
    • Run() is a static method that has a loop to process the event messages
    • The Main() is very small !
  • Constructor of Form1() calls InitializeComponent()
    • InitializeComponent() simply create all the GUI controls and add them to the container of Form1
  • Dispose()
    • Call by application in exit to free unmanaged resources (more about this later)
initializecomponent
InitializeComponent()

#region Windows Form Designer generated code

private void InitializeComponent() {

this.button1 = new System.Windows.Forms.Button();

this.button1.Text = "Click Me !";

this.Controls.Add(this.button1); //add to container

. . .

}

#endregion

  • Controls is a Property
    • this.Controls return a reference to a container
slide29

Class diagram of Window’s Form

Object

MarshalByRefObject

Control.ControlCollection

1

Component

Control

*

PictureBox

ScrollableControl

ButtonBase

Button

Panel

ContainerControl

Form

class diagram of window s form
Class diagram of Window’s Form
  • Where is the container?
  • How does this class structure supports composition (has-a) relationship?
  • What is the equivalent of class Glyth in this structure?
invalidate
Invalidate()
  • A single command that invokes the action of redrawing all the GUI items in Form
  • Invoke whenever the window is dirty
    • e.g. resize, expose, …
  • Window server calls this.Invalidate(), which sends a message to the message queue that will be processed by the Application.Run() loop
  • Form ask all Controls in its container to draw itself
  • Each Control asks Controls in its container to draw itself (recursion)
unmanaged resource
Unmanaged resource
  • Unmanaged resource is resource that is not managed by the garbage collector
    • e.g. memory obtained using C’s malloc()
      • Must be deleted by the user code
  • When GC is invoked, it calls Finalize() automatically
    • Finalize() is the C# destructor (opposite of constructor)
    • Contain user code to remove unmanaged resource
    • If you don’t have unmanaged resource, then you don’t need to write object.Finalize()
dispose
Dispose()
  • Problem with Finalize()
    • Finalize()can only be invoked by GC, but GC is only called when system runs out of memory
    • For critical resources, this is too
    • e.g. opened file, opened database connection, want to close as soon as possible
  • Solution
    • Called Dispose() explicitly
    • If you use Dispose(), then you should call GC.SuppressFinalize()to suppress Finalize()
    • Otherwise the object will be clear twice
dispose1
Dispose()
  • Finalize() is a method in System.Object
    • Supported by all classes
  • Dispose() is NOT a method in System.Object
    • For an object to support Dispose(), must inherit the IDisposable interface and implement the only function Dispose()
  • If you don’t need Dispose(), the base class Form provides a do-nothing default
  • You cannot use Dispose() to remove managed resource, managed resource can only be released by GC
using
Using
  • This special construct calls Dispose()automatically when it is out of scope
  • Standard usage

static void Main() {

using (Form1 frm = new Form1()) {

Application.Run(frm);

} //frm.Dispose() called here

}

net remoting layer
.Net Remoting layer
  • How to simplify network programming?
  • Some key terms
    • Object serialization
    • Proxies
    • Marshaling by reference / value
    • Server activated objects
serialization
Serialization
  • Convert the state of an object to a linear sequence of data, and send the byte-stream to another computer
  • Use the [Serializable] attribute to mark an object serializable

[Serializable]

public class Student {

. . .

}

  • Otherwise, .NET won’t serialize the object, for security reason
serialization formatter
Serialization Formatter
  • Formats to choose in sending the serialized objects
    • Binary format
    • SOAP (Simple Object Access Protocol) format
    • XML format
  • Pick one you like, all does the same thing
  • using System.Runtime.Serialization.Formatters.Binary;
  • using System.Runtime.Serialization.Formatters.Soap;
  • Using System.Xml.Serialization.XmlFormatter
saving objects to file by serialization
Saving objects to file by serialization
  • //save object to file

Student s = new Student();

FileStream fs = File.Create(“student.dat”);

BinaryFormatter format = new BinaryFormatter();

format.Serialize(fs, s);

  • //retrieve the object from file

FileStream fs = File.OpenRead(“student.dat”);

Student s = (Student)format.Deserialize(fs);

net remoting
.NET Remoting
  • Client
    • The one who wants to use a remote object
  • Server
    • The one who provides the remote object
  • Marshaling
    • Describes how a remote object is passed to client
    • Marshal-by-value (MBV)
      • Client gets a copy of the remote object
    • Marshal-by-reference (MBR)
      • Client gets a proxy of the remote object
slide41
MBV
    • Server passes a copy of remote object to client
    • Any modification by the client won’t affect the original object in the server side
  • MBV
    • server passes a proxy of the object to the client, the proxy acts as a reference to the object
    • Any modification by the client changes the original object in the server side
key elements in remoting
Key elements in Remoting
  • Proxy
    • The local object in the client side that impersonates the remote object
  • Formatter
  • Channel : TCP / HTTP

Client object

Remote object

Proxy

Channel

Formatter

Formatter

client server programming using net remoting
Client-server programming using .NET Remoting
  • A simple client-server program in OO
    • Client gets a copy or a proxy of the remote object
    • Use the object to send a message to server
    • Server returns a message to client
  • Example : creates 3 projects
    • SimpleClient.cs
    • SimpleServer.cs
    • Remote.cs
      • Class for the remote object
      • Use by both SimpleClient and SimpleServer
remote cs
Remote.cs

//The MBR object at the server side

using System;

namespace RemoteLib {

public class RemoteHello : MarshalByRefObject {

public void SendMsg(string str) { //from client

Console.WriteLine("{0}",str);

}

public string ReceiveMsg(){ //server’s response

return "hello world";

}

}

}

simpleserver cs
SimpleServer.cs

using System;

using System.Runtime.Remoting;

using System.Runtime.Remoting.Channels;

using System.Runtime.Remoting.Channels.Http;

using RemoteLib;

namespace SimpleServer {

class Server {

static void Main() {

HttpChannel c = new HttpChannel(12345);

ChannelServices.RegisterChannel(c);

RemotingConfiguration.RegisterWellKnownServiceType(

typeof(RemoteHello), "RemoteHelloObj.soap",

WellKnownObjectMode.Singleton); //start the server

Console.ReadLine(); //to quit, just type something

}

}

}

simpleclient cs
SimpleClient.cs

using System;

using System.Runtime.Remoting;

using System.Runtime.Remoting.Channels;

using System.Runtime.Remoting.Channels.Http;

using RemoteLib;

class Client {

static void Main() {

HttpChannel c = new HttpChannel();

ChannelServices.RegisterChannel(c);

object remoteObj=Activator.GetObject(typeof(RemoteHello),

"http://localhost:12345/RemoteHelloObj.soap");

RemoteHello simple = (RemoteHello) remoteObj; //casting

simple.SendMsg("hello from client");

Console.WriteLine(“From server:{0}", simple.ReceiveMsg());

}

history of distributed computing
History of Distributed Computing
  • 1980 Remote Procedure Call (RPC)

(to invoke functions in a remote machine)

  • 1990 ORPC (Object-RPC)

(to invoke methods in a remote object)

  • 1990 CORBA by OMG (Object Management Group)

Common Object Request Broker Architecture

To support communication at object level in a

heterogeneous environment

key components in corba
Key Components in CORBA
  • IDL Interface Definition Language
  • ORB The middleware that takes care of the

communication between objects, e.g.

method invocation, parameters passing

IDL interface

server

client

IDL interface

ORB

stub

skeleton

Network

other similar models
Other similar models
  • DCOM by Microsoft
    • (Distributed Component Object Model)
  • RMI by Java
    • (Remote Method Invocation)
  • Limitations
    • DCOM and Java are platform specific
    • For CORBA, nodes must run the same ORB
      • ORBs from different vendors may have interoperability problems
slide50
Interoperability issue
    • Advent of e-commerce, want distributed computing to be more widely available
    • With DCOM, RMI, or CORBA, the chances that both ends run the same platform is not high
  • 2000 IBM and Microsoft proposed the web

services which forms the basis for SOA

(Service Orientated Architecture)

slide51
SOA
  • Power plant example
    • A hundred years ago, each family had its own power generator
    • Complex, you need to know how to fix the machine
  • What happened next
    • Development of power transmission grid
    • Simple interface at client side (just a switch)
    • Complexity of power generation at the power plant side (the server)
  • Web services plan to follow the same development
    • Complex server, thin clients
key issues in soa
Key Issues in SOA
  • How to describe the interface of a remote object?
    • By WDSL (Web Services Description Language)
    • Describes the interface in XML (replace IDL)
  • How to communicate with the remote object?
    • By SOAP (Simple Object Access Protocol)
    • To invoke a method, send a message that has the name of the method and parameters
  • How to find objects that provide the services?
    • By UDDI (Universal Description, Discovery and Integration)
    • A directory service to search for web services
web services model
Web services model

Server

Client

HTTP/SOAP

Concrete

Object

Proxy object

URI

Interface

wsdl is just a xml file
WSDL is just a XML file

portType is similar to class

<portType name=“Stock"><operation name="getPrice"> <input message="getPriceRequest"/> <output message="getPriceResponse"/></operation>

</portType>

<message name="getPriceRequest">

<part name=“StockName" type="xs:string"/>

</message>

<message name="getPriceResponse">

<part name=“Price" type="xs:string"/>

</message>

Method in a class

slide55
WSDL
    • Use XML to describe a class
    • .NET can generate the WSDL file automatically from a class definition
  • Client can download the WSDL file, and use it to create proxy objects
  • Many companies already provide the web services, e.g. Amazon, Google
a soap request to the server
A SOAP request to the server

POST /InStock HTTP/1.1 Host: www.stock.org

<?xml version="1.0"?>

<soap:Envelope

xmlns:soap="http://www.w3.org/2001/12/soap-envelope">

<soap:Body xmlns:m="http://theURIofThisNameSpace">   

<m:GetPrice>

<m:StockName> HSBC </m:StockName>     

</m:GetPrice>

</soap:Body>

</soap:Envelope>

Schema

Namespace of SOAP

Schema of your namespace m

parameter

method

a soap response from server
A SOAP response from server

HTTP/1.1 200 OK

<?xml version="1.0"?>

<soap:Envelope

xmlns:soap="http://www.w3.org/2001/12/soap-envelope">

<soap:Body xmlns:m="http:// theURIofThisNameSpace ">

<m:GetPriceResponse>

<m:Price>34.5</m:Price>

</m:GetPriceResponse>

</soap:Body>

</soap:Envelope>

xml scheme
XML-Scheme
  • Schema is a document that describes the abstract structure of a data set
    • Like what you have done to describe the structure of a class
  • XML schema provides a list of names (types) that are used to define complex data structure (similar to how you define a class or structure)
    • e.g a string type can be described by xs:string
why use xml
Why use XML?
  • Syntax-wise XML file is similar to HTML
  • The main reason of using XML is that it supports namespaces
  • Namespace solved the problem of name collision
  • An XML namespace is a collection of names, identified by the URI reference
  • Elements in the XML namespace is defined by the schema
key advantages of web services
Key advantages of web services
  • Free (Web Services) vs fee economic model ( CORBA)
  • Communication via HTTP port 80 channel
    • Firewall friendly
  • Use widely accepted standards
    • Method invocation is via SOAP messages encoded in XML
    • Interface definition is by WSDL, also in XML
    • Interoperability problem solved by using protocol based on SOAP and XML
  • Any node that supports HTTP, WSDL, and SOAP can be connected to SOA