Upload
dusan
View
41
Download
0
Embed Size (px)
DESCRIPTION
Using Patterns Examples. Dr. Neal CIS 480. Singleton Pattern Concept. Singleton Pattern: For those situations when you only one object to be created from a particular class. This means that only one instantiation of the class is allowed. - PowerPoint PPT Presentation
Citation preview
Using Patterns ExamplesUsing Patterns Examples
Dr. NealDr. Neal
CIS 480CIS 480
Singleton Pattern ConceptSingleton Pattern Concept
• Singleton Pattern:– For those situations when you only one object to be created from a particular
class.– This means that only one instantiation of the class is allowed.– The first reference to the class will create the instance and all future references
will return this same instance.– Therefore the class must control that only one instance of itself is created.
• Our Example:– This example is a web site with a home page and two product pages that the
user may shop for furniture and lamps.– The user may add items to their shopping cart on each of the product pages.– In addition to keeping tract of a users purchases we would also like to keep a
count of how many times each page is visited on the site.– We will create to classes a CartManager (keep tract of purchases) and
PageCounter (keep tract of page counts)– The home page will also allow display of the cart contents and the current status
of page counts.
PageCounter ClassPageCounter Class
• Our Page Manager:– Only a single instance of PageCounter must exist for
the entire application.– The first call to PageCounter must create an instance
of the class and all other calls will reference it.– This means that all users will see the same
PageCounter object.– It must keep tract of the “get” request for each page in
our application and increment the page counts. – It must provide methods for incrementing the count
per page and retrieving all page counts
CartManager ClassCartManager Class• Our Shopping Cart:
– We what only one instance of a shopping CartManager per user or session that keeps track of all user purchases.
– This means that there will multiple carts if more than one user is accessing the application.
– This one instance of the CartManager for a user must live across multiple pages while the user is shopping.
– The CartManager should be accessible from anywhere so new products can be added from any page.
– The CartManager needs to provide methods for us add contents as well as to access the contents.
Contents of cart
Page Counts
DesignDesignClassesClasses
CartManager
al : ArrayList
getCartManager()add()CartManager()Al()
(from Business Services)
<<control>>
Home
lblHeader : LabellnkProductsOne : LinklnkProductsTwo : LnikbtViewCartContents : ButtonlblContents : LabellblPageCounts : Label
productOneClick()Home()productTwoClick()viewCartContentsClick()viewPageCountsClick()
(from Web Interface)
<<boundary>>
ProductsOne
lblHeader : LabelchklProducts : CheckBoxListbtnAddAProduct : ButtonbtnReturn : Button
ProductsOne()addAProductClick()returnClick()
(from Web Interface)
<<boundary>>ProductsTwo
lblHeader : LabelchklProducts : CheckBoxListbtnAddProduct : ButtonbtnReturn : Button
ProductsTwo()returnClick()addAProductClick()
(from Web Interface)
<<boundary>>
PageCounter
pc : PageCounterct : int[]al : ArrayList
PageCounter()getPageCounter()countPage()getCounts()
(from Business Services)
SequenceSequenceDiagramDiagram
SequenceSequenceDiagramDiagram
(cont)(cont)
using System;using System.Collections;
namespace Patterns{
/// <summary>/// Dr. Neal/// CIS 480/// Example of singleton pattern used for a Page Counter and a modified /// singleton pattern for a Cart Controller /// </summary>public class PageCounter{
private static PageCounter pc;private int[] ct;private ArrayList al;
// the page counts are kept in the int array and their corresponding// page names are kept in the arraylistprivate PageCounter(){
ct = new int[4];al = new ArrayList();
}
// create the singleton object on the first call and return its // instance for each subsequent call, this creates one pagecounter// for the entire application across all user sessionspublic static PageCounter getPageCounter(){
if (pc == null){
pc = new PageCounter();}return pc;
}
Store in static attribute
PageCounter Class
Static declarationArrays for counts
& pages
// the countPage method insures that the page has been visited before// if not is added to the arraylist, then the position in the arraylist// is used to index the int counter arraypublic void countPage(string page){
if (! al.Contains(page)){
al.Add(page);}ct[al.IndexOf(page)] += 1;
}
// to retrieve the values of page counts a hashtable is built with// the page as a key and the counts as the value objectspublic Hashtable getCounts(){
Hashtable ht = new Hashtable();foreach (Object o in al){
ht.Add(o, ct[al.IndexOf(o)]);}return ht;
}
}}
Add page to arraylist and use its index to increase
count int array
Fill a hashtable for return with page as key and count as
value
PageCounter Class
using System;using System.Collections;
namespace Patterns{
/// <summary>/// Dr. Neal/// CIS 480/// Example of singleton pattern used for a Page Counter and a modified /// singleton pattern for a Cart Controller /// </summary>public class CartController{
private ArrayList al;
//Array List is used to store cart itemsprivate CartController(){
al = new ArrayList();}
// this static method is called on the class to get the instance of// the cartcontroller that is associated with the current session// if the instance doesn't exist then it is created and stored in the// current session, this creates one cartcontroller per session public static CartController getController(System.Web.SessionState.HttpSessionState s){
if (s["Cart"] == null){
s["Cart"] = new CartController();}return (CartController) s["Cart"];
}
Static declaration
Create instance if it doesn’t exist
Store in session so one per user
CartManager Class
// the add method just adds whatever object it is handed to the arraylist// which are the contents of the shopping cartpublic void add(Object o){
al.Add(o);}
// this property allows access to the arraylist that contains our cart entriespublic ArrayList Al{
get { return al;}}
}}
Add cart contents
Get cart contents
CartManager Class
Class, Session, and Instance Class, Session, and Instance Variables/MethodsVariables/Methods
Static Space(Class)
One per application
Object Space(Instance)One per object
Session["Cart"]
int[] ct
void countPage()void add()
instance methods
instance attributes
Session Space(per User)One per user
static PageCounter pc
static PageCounter getPageCounter()
Static attribute
static CartController getController() Static methods
Sessionattribute
ArrayList al
Method Calls Method Calls
cc.add();
CartController.getController() Static call referencingthe class name which is loaded when the application starts
Call referencing aninstance of the objectof type CartController
Static Method Call
Instance Method Call
Object Life During ProcessingObject Life During Processing
ProductPageOne(ProductOne.aspx.cs)
HomePage(Home.aspx.cs)
ProductPageTwo(ProductTwo.aspx.cs)
CartManager
HomePage(Home.aspx)
ProductPage(ProductOne.aspx)
ProductPage(ProductTwo.aspx)
Onlyalive in browseron client
Only alive as page isexecutedduring therequest& response
Alive forthe entireuser session
Alive forthe applicationPageCounter