610 likes | 783 Views
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.
E N D
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? • 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 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 • 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 • 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
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 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 • 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 • 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 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 • 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 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 • 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 • 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 • 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 • 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 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 • 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 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 • 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 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 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 • 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 • In ToolBox window, drag a Button object and drop it to the position you want in the Form
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) 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 • 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() #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
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 • 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() • 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 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() • 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
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 • 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 • How to simplify network programming? • Some key terms • Object serialization • Proxies • Marshaling by reference / value • Server activated objects
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 • 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 • //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 • 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
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 • 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 • 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 //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 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 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 • 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 • 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 • 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
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)