Document Sample
L3 Powered By Docstoc
					        Case Study
Department of Information Engineering   231
Case study
• GUI (Graphical User Interface) toolkit
  – A typical GUI has many different objects
     • Menu, window, button, scrollbar, . . .
  – Hierarchical (tree-like) structure
     • Like a file directory
     • A window has several windows and buttons

• OO provides an elegant solution to GUI problems
  – Most successful example – Apple Macintosh

Department of Information Engineering          232
How to draw GUI objects?
• Put all concrete objects into a Glyph
  container; ask each Glyph to draw itself
      Glyph container

                Glyph                   Add   (System provided)
                                               Concrete Glyph
                                               (user provided)

Department of Information Engineering                            233
How to draw GUI objects?
• Glyph[] window = {new Button(),
                    new ScrollBar()};
  foreach (g in Window) g.Draw();

                        virtual void Draw()

     Button                       ScrollBar     Panel
     void Draw()                  void Draw()   void Draw()

Department of Information Engineering                         234
Upcasting and polymorphism
• Create concrete objects
   – new Button(), new ScrollBar()};

• Add to an abstract container
   – Container only knows abstract base class

• Upcasting
   – Button is upcasted to Glyph

• Polymorphism
   – All concrete objects are treated uniformly
     (same) as Glyph
   – foreach (g in Window) g.Draw();
Department of Information Engineering             235
• Is Window a kind of glyph?

• Yes, window shares many common properties
  with buttons, scroll bars, panel, . . .
   – Is-a relationship = inheritance



      Window                Button      ScrollBar   Panel

Department of Information Engineering                       236
• But Window can have some buttons, scroll bars,
   – Has-a relationship = composition
   – Window has a number of glyphs

               Window              has-a    Glyph


                           Button          ScrollBar   Panel

Department of Information Engineering                          237
Is-a and Has-a relationships
Is-a                                    Has-a
• Inheritance                           • Composition
• Window is-a Glyph                     • Window has-a few
                                          buttons, windows

• class Window : Glyph                  • class Window {
  {                                          Glyph[] g;
       . . .                                 . . .
   }                                       }

Department of Information Engineering                        238
Composite pattern
• Combining is-a and has-a
   – class Window : Glyph {                             //inheritance
       Glyph[] g;                                       //composition
       . . .

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


                     Window             Button    ScrollBar    Panel
Department of Information Engineering                               239
An even more general form of composite 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

           Window              Button       ScrollBar   Panel

Department of Information Engineering                           240
An even more general form of composition pattern
• class Window : Glyph {
       . . .
• Window inherits the Glyph container from
   – Support Window inside a Button

          Window               Button       ScrollBar   Panel

Department of Information Engineering                           241
Limitation of inheritance
• How to change to a different Button at run time?

      Glyph container

                Glyph                   Add   (System provided)
                                               Concrete Glyph
                                               (user provided)

Department of Information Engineering                            242
Limitation of inheritance
• Base class’s Draw() is overrided by the subclass

• The actual Draw() is done by the concrete

• To draw a different look-and-feel button?
   – Tedious, has to replace the old Button object
     in the container by a new one that has a
     different Draw()

Department of Information Engineering            243
• 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

                         Add        Glyph
  Glyph                           DrawStyle obj;
  Draw()                                                 DrawStyle
                                  Draw(){                Draw()
  Glyph                             obj.Draw()
  Draw()                          }
  Glyph                           ChangeStyle(
  Draw()                            DrawStyle newobj){
                                    obj = newobj;
Department of Information Engineering                           244
The essential ideas of OO
   – Similar types of objects that share the same

   – An object that is made up from other objects

   – To outsource work to another object
   – Delegation has the same syntax as composition

Department of Information Engineering               245
Design of Callback
• What is callback?
  – The mechanism of sending messages between
  – e.g. a mouse button is clicked, how to send this
    mouse-up event message to a mouse-up

• Window Server
   – Contains GUI objects (Button, 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()
Department of Information Engineering            246
Callback by inheritance
• Build the MyWindow class inherited from Form
  (Form is like Glyph in prev example)
• Override OnClick()
• Add concrete MyWindow object to container as
  Window Server
         Form (Button)                  Form
         virtual OnClick()              virtual OnClick()

         Form (ScrollBar)
         virtual OnClick()              MyWindow
                                        override OnClick()

Department of Information Engineering                   247
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 to parent (Form)
  }           //in case there are more things to do

Department of Information Engineering           248
OO in one picture


Department of Information Engineering                249
OO is like a basket of fruits
• The basket is a container of fruits

• Important
   – You have just made an abstraction
   – Physically the container has different concrete
     objects (apples and oranges), but because of
     your abstraction, you have generalized them
     as fruits
   – You don’t see apples, oranges, only fruits
      • Program to an interface, not implementation

• You use the objects as fruits (interface), not
  apples and oranges (implementation)
Department of Information Engineering              250
Your abstract view
• Program to an interface, not an implementation
   – Abstract and flexible programming



Department of Information Engineering              251
Your abstract view
• What if you eat a fruit?

• Pick a fruit object from the container and eat it
   – fruit.Eat()

• What happens next?
  – If fruit is an Apple, it tastes like an apple
  – If it is an Orange, it tastes like an orange

• Your leave the actual implementation to the
  hidden concrete objects

Department of Information Engineering                 252
The concrete view
• What actually happens
     Fruit                 Fruit                Eat()
     Eat()                 Eat()

                                        Apple   Orange   Banana
    Apple                Orange         Eat()   Eat()    Eat()
    Eat()                Eat()

Department of Information Engineering                       253
Library application

      Lendable                                     Borrow()

                                        Book       DVD        Journal
      Lendable                                                Borrow()
                                        Borrow()   Borrow()


Department of Information Engineering                               254
Bank application

    Account                                         Deposit()

     Account                            Saving      Current     USD
     Deposit()                          Deposit()   Deposit()   Deposit()


Department of Information Engineering                                255
Game application
• Attack() is done by collision detection of
    Fighter                                    Attack()

    Fighter                         Naruto     Sakura     Sasuke
    Attack()                        Attack()   Attack()   Attack()


Department of Information Engineering                          256
Callback by delegation
• Store a handler pointer into an object of type

• Add the EventHandler object to Form

    Window server

                                        EventHandler      obj
                                        obj.Handler()     Handler()

                                        Point to a handler function

Department of Information Engineering                             257
  Callback by delegation
class MyWindow : Form {
 static void Main() {
  Application.Run(new MyWindow());
                                                       function pointer
public MyWindow() {
 this.MouseUp += new EventHandler(this.Handler());
} //MouseUp is a container

                                          Handler function
 private void Handler(object sender,System.EventArgs e){
  Console.WriteLine(“call from {0}”,sender.ToString());
  Department of Information Engineering                               258
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

Department of Information Engineering               259
Delegate – how to Build 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 creates the class MyHandler for
   – A MyHandler object can encapsulate any function
     pointer with a matched signature (void and

Department of Information Engineering              260
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());
                                        The function pointer
 foreach ( (Callback) obj in list)
}                               This object function
                                        is called from list
Class Client {
 private void Notify(String s) {
   Console.WriteLine(“call from {0}”,s);
Department of Information Engineering                    261
Game application
• Implementation reuse is best done by delegation
    Fighter                             Attack()

    Fighter                     ConcreteFighter
    Attack()                    Image _image;
                                Weapon _w;                Weapon
                                Attack() {
                                }                  Fire        Sand
                                                   Attack()    Attack()
Department of Information Engineering                                262
Visual Studio – Window Forms
• Tool that helps you to design a GUI easily
   – Open a new project and choose Window
   – Drag and drop GUI into the Form

Department of Information Engineering          263
Add a Button
• In ToolBox window, drag a Button object and
  drop it to the position you want in the Form

Department of Information Engineering            264
What Visual Studio has done
• Initially Visual Studio has an empty container

• Your action (dragging a button) causes
    – A button is created and added to the container
    – Visual Studio then asks objects in the
      container to draw themselves, that is why you
      see the button

Department of Information Engineering              265
Change Button’s properties
• Can resize and move the button, and use the
  Properties window of the button to change the

Department of Information Engineering             266
What Visual Studio has done
• Your action (select the button) causes
    – Collision detection
       • Visual Studio checks the mouse pointer
         position and sees which object in its
         container is hit
       • Find the button object
• Your further action acts on the button invokes
  methods inside the button which change the
  attributes of the button

Department of Information Engineering              267
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() {
 private void InitializeComponent() {
   this.button1 = new System.Windows.Forms.Button();
   //. . .
 protected override void Dispose( bool disposing ) {
   //. . .
Department of Information Engineering              268
• 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() 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)
Department of Information Engineering                269

#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
  . . .

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

Department of Information Engineering           270
What Visual Studio has done
• InitializeComponent() is the main part in the code
   generation (the rest are just boilerplate code)

• Visual Studio simply asks each object in its
  container to output code based on its stored
   – A button would simply generate the
     constructor code and the Text code, then adds
     itself to the container this.Controls
   – this.Controls is used by window server for
     collision detection, etc

Department of Information Engineering                271
Class diagram of Window’s Form                         Object

Control.ControlCollection                      MarshalByRefObject


           PictureBox                ButtonBase        ScrollableControl

                                          Button   Panel     ContainerControl

  Department of Information Engineering                                    272
Class diagram of Window’s Form
• Where is the container?

• How does this class structure supports composition (has-
  a) relationship?
   – Each Control has a ControlCollection
   – Each ControlCollection can have many

• What is the equivalent of class Glyth in this structure?
  – Control

Department of Information Engineering                   273
• 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)
Department of Information Engineering                 274
Unmanaged resource
• Unmanaged resource is resource that is not managed by
  the garbage collector (e.g. memory obtained from C’s
  malloc(), must be deleted by the user)
• Managed resource is a key advantage of C#/Java over

• When garbage collector is invoked, it calls Finalize()
   – Finalize() is the C# destructor (opposite of
   – Can have user code to remove unmanaged resource
   – If you don’t have unmanaged resource, then you don’t
     need to write object.Finalize()

Department of Information Engineering                275
• 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 late
   – 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
    – Otherwise the object will be clear twice
Department of Information Engineering                  276
• 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()

• Base class Form support IDisposable , it provides a do-
  nothing default

• You cannot use Dispose() to remove managed resource,
  managed resource can only be released by garbage
Department of Information Engineering                277
• The special construct Using calls Dispose()
  automatically whenever it is out of scope

• Standard usage
   static void Main() {
      using (Form1 frm = new Form1()) {
      } //frm.Dispose() called here

Department of Information Engineering           278
      Web Services
Department of Information Engineering   279
.Net Remoting layer
• How to simplify network programming?

• Some key terms
   – Object serialization
   – Proxies
   – Marshaling by reference / value
   – Server activated objects

Department of Information Engineering    280
• Convert the state of an object into a linear sequence of
  byte stream, and send it to another computer

• To make an object serializable, label the class with
  [Serializable] attribute

    public class Student {
     . . .

• Default is no serialization, for security reason

Department of Information Engineering                    281
  Serialization Formatter
• Different formats for sending the serialized objects
   – Binary format
   – SOAP (Simple Object Access Protocol) format
   – XML format

• using System.Runtime.Serialization.Formatters.Binary;
• using System.Runtime.Serialization.Formatters.Soap;
• Using System.Xml.Serialization.XmlFormatter

• SOAP is XML-based
• SOAP and XML use ascii characters, can be read by human

   Department of Information Engineering                 282
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);

Department of Information Engineering             283
.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

Department of Information Engineering                   284
  – Server passes a copy of remote object to client
  – Any modification by the client won’t affect the
    original object in the server side

  – 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

Department of Information Engineering                    285
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


             Formatter                  Channel    Formatter

Department of Information Engineering                             286
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
Department of Information Engineering                     287
//The MBR object at the server side

using System;

namespace RemoteLib {
 public class RemoteHello : MarshalByRefObject {

  public void SendMsg(string str) { //from client
  public string ReceiveMsg(){ //server’s response
    return "hello world";

Department of Information Engineering              288
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);
       typeof(RemoteHello), "RemoteHelloObj.soap",
       WellKnownObjectMode.Singleton); //start the server
     Console.ReadLine();   //to quit, just type something
Department of Information Engineering                 289
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();
 object remoteObj=Activator.GetObject(typeof(RemoteHello),
 RemoteHello simple = (RemoteHello) remoteObj; //casting
 simple.SendMsg("hello from client");
 Console.WriteLine(“From server:{0}", simple.ReceiveMsg());

Department of Information Engineering                290
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

Department of Information Engineering              291
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

  client               IDL interface         IDL interface    server


Department of Information Engineering                              292
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, both sides must run the same
      • ORBs from different vendors may have
        interoperability problems

Department of Information Engineering          293
• Interoperability issue
   – Advent of e-commerce, want distributed
     computing to be more widely available
   – With DCOM, RMI, or CORBA, the chance 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)

Department of Information Engineering                    294
• Power plant example
   – A hundred years ago, each family had its own
     power generator
   – Complex, you need to know how to fix the

• 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
     – Complex server, thin clients
 Department of Information Engineering                295
• The ultimate web service

Department of Information Engineering   296
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

Department of Information Engineering                    297
Web services model


                           HTTP/SOAP                       Concrete
Proxy object                             URI   Interface

 Department of Information Engineering                         298
WSDL is just a XML file                 portType is similar to class

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

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

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

Department of Information Engineering                           299
  – 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

Department of Information Engineering                300
A SOAP request to the server
POST /InStock HTTP/1.1 Host: www.stock.org

<?xml version="1.0"?>
                       Namespace of SOAP   Schema

<soap:Body xmlns:m="http://theURIofThisNameSpace">
  <m:GetPrice>          Schema of your namespace m
    <m:StockName> HSBC </m:StockName>
</soap:Body>      method


Department of Information Engineering           301
A SOAP response from server
HTTP/1.1 200 OK

<?xml version="1.0"?>

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


Department of Information Engineering           302
• 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

Department of Information Engineering             303
Why use XML?
• Syntax-wise XML file is similar to HTML

• The main reason of using XML is that it supports

• 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

Department of Information Engineering            304
Key advantages of web services
• Free (Web Services) vs fee economic model (
• 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
Department of Information Engineering            305

Shared By: