Patterns Singleton Memento Flyweight

Embed Size (px)

Citation preview

  • 8/9/2019 Patterns Singleton Memento Flyweight

    1/35

    1

    TCSS 360, Spring 2005

    Lecture Notes

    Design Patterns:

    Singleton, Memento, l!"eig#t

  • 8/9/2019 Patterns Singleton Memento Flyweight

    2/35

    2

    $utline

    Singleton pattern

    Seriali%a&le inter'ace an( persistent

    o&)ects

    l!"eig#t pattern

  • 8/9/2019 Patterns Singleton Memento Flyweight

    3/35

    3

    Pattern: Singleton

    a class that has only oneinstance

  • 8/9/2019 Patterns Singleton Memento Flyweight

    4/35

    4

    *estricting o&)ect creation

    pro&lem: sometimes "e "ill reall! onl! e+ernee( one instance o' a particular class eamples: -e!&oar( rea(er, &an- (ata collection "e.( li-e to ma-e it illegal to #a+e more t#an one,

    )ust 'or sa'et!.s sa-e

    "#! "e care:

    creating lots o' o&)ects can ta-e a lot o' time etra o&)ects ta-e up memor! it is a pain to (eal "it# (i/erent o&)ects oating

    aroun( i' t#e! are essentiall! t#e same

  • 8/9/2019 Patterns Singleton Memento Flyweight

    5/35

    5

    Singleton pattern

    singleton: an o&)ect t#at is t#e onl! o&)ect o' itst!pe ensures t#at a class #as at most one instance pro+i(es a glo&al access point to t#at instance

    ta-es responsi&ilit! o' managing t#at instancea"a! 'rom t#e programmer illegal to constructmore instances

    pro+i(e accessor met#o( t#at allo"s users tosee t#e one an( onl! instance

    possi&l! t#e most -no"n popular (esignpattern4 t#is s#oul( tell !ou somet#ing

  • 8/9/2019 Patterns Singleton Memento Flyweight

    6/35

    6

    *estricting o&)ects,continue(

    $ne "a! to a+oi( creating o&)ects:use static met#o(s instea( Math, System, JOptionPane

    is t#is a goo( alternati+e c#oice #! or "#!not

    Pro&lem: lac-s ei&ilit! 7ample: static met#o(s can.t &e passe( as

    an argument to a met#o(, nor returne(

    Pro&lem: cannot &e eten(e(

    7ample: static met#o(s can.t &e su&classe(an( o+erri((en li-e a sin leton.s coul( &e

  • 8/9/2019 Patterns Singleton Memento Flyweight

    7/35

  • 8/9/2019 Patterns Singleton Memento Flyweight

    8/358

    Singleton seuence(iagram

  • 8/9/2019 Patterns Singleton Memento Flyweight

    9/359

    consi(er a singleton class *an(om;eneratort#at generates ran(om num&ers

    public class RandomGenerator {

    private static RandomGenerator gen = newRandomGenerator()

    public static RandomGenerator getInstance(){ return gen

    !

    private RandomGenerator(){!

    public double ne"t#umber() {

    return Math$random()

    !

    !

    possi&le pro&lem: al"a!s creates t#e instance,e+en i' it isn.t use(

    Singleton eample

  • 8/9/2019 Patterns Singleton Memento Flyweight

    10/3510

    +ariation: (on.t create t#e instance untilnee(e(

    %% Generates random numbers$

    public class RandomGenerator { private static RandomGenerator gen & null

    public static RandomGenerator getInstance() {

    i' (gen && null)

    gen & ne RandomGenerator()

    return gen !

    !

    #at coul( go "rong "it# t#is +ersion

    Singleton eample 2

  • 8/9/2019 Patterns Singleton Memento Flyweight

    11/3511

    +ariation: sol+e concurrenc! issue &!loc-ing

    %% Generates random numbers$

    public class RandomGenerator { private static RandomGenerator gen & null

    public static synchronized RandomGenerator getInstance() { i' (gen && null)

    gen & ne RandomGenerator() return gen

    !

    !

    9s an!t#ing "rong "it# t#is +ersion

    Singleton eample 3

  • 8/9/2019 Patterns Singleton Memento Flyweight

    12/3512

    +ariation: sol+e concurrenc! issue "it#outunnecessar! loc-ing

    %% Generates random numbers$

    public class RandomGenerator {

    private static RandomGenerator gen & null

    public static RandomGenerator getInstance() {

    i' (gen && null) {

    synchronized (RandomGenerator.class) { // must test again can you see why! i" (gen == null) gen & ne RandomGenerator()

    # !

    return gen

    !!

    Singleton eample o"> to output an( 'rom inputstreams

    can represent man! (ata sources: Ales on #ar( (is-

    anot#er computer on net"or-

    "e& page input (e+ice

    -e!&oar(, mouse, etc=

  • 8/9/2019 Patterns Singleton Memento Flyweight

    18/3518

    Stream #ierarc#!

    java.io.InputStream

    udioInputStream

    *ileInputStream

    Ob+ectInputStream

    java.io.OutputStream,yterrayOutputStream

    *ileOutputStream

    Ob+ectOutputStream

  • 8/9/2019 Patterns Singleton Memento Flyweight

    19/35

  • 8/9/2019 Patterns Singleton Memento Flyweight

    20/35

  • 8/9/2019 Patterns Singleton Memento Flyweight

    21/35

    21

    Seriali%ation eample

    recommen(ation: use a Memento class t#at #assa+eloa( co(e

    %% rite the ob+ect named someObjectto 'ile .'ile$dat.

    try {

    OutputStream os & ne *ileOutputStream(.file.dat.)

    Ob+ectOutputStream oos & ne $b%ect$utput&tream(os)

    oos$write$b%ect(someObject)

    os$close()

    ! catch (IO-"ception e) { $$$ !

    %% load the ob+ect named someObject'rom 'ile .'ile$dat.

    try {

    InputStream is & ne *ileInputStream(.file.dat.)

    Ob+ectInputStream ois & ne $b%ectInput&tream(is)

    rray/ist some/ist & (rray/ist)ois$read$b%ect()

    is$close()! catch (-"ception e) { $$$ !

  • 8/9/2019 Patterns Singleton Memento Flyweight

    22/35

    22

    Memento seuence(iagram

  • 8/9/2019 Patterns Singleton Memento Flyweight

    23/35

    23

    must implement t#e met#o(less+ava$io$Seriali0ableinter'ace 'or !our class to &ecompati&le "it# o&)ect inputoutput streams

    public class ,an1ccount implements &erializable

    {

    $$$

    ensure t#at all instance +aria&les insi(e !ourclass are eit#er seriali%a&le or (eclare(transient

    transient Ael(s "on.t &e sa+e( "#en o&)ect is seriali%e(

    Ma-ing !our classesseriali%a&le

  • 8/9/2019 Patterns Singleton Memento Flyweight

    24/35

    24

    Let.s ma-e our singleton game mo(elseriali%a&le

    #at can #appen i' a singleton is sa+e(an( loa(e( 9s it possi&le to #a+e more t#an one instance

    o' t#e singleton.s t!pe in our s!stem Does t#is +iolate t#e Singleton pattern ill

    it &rea- our co(e 9' so, #o" can "e A it

    Bac- to singleton===

  • 8/9/2019 Patterns Singleton Memento Flyweight

    25/35

    25

    Singleton eample 5

    +ariation: #as strict c#ec-s to ma-e suret#at "e #a+e not sa+e( a stale re'erenceto t#e singleton o&)ect

    %% Generates random numbers$public class RandomGenerator {

    private static RandomGenerator gen & null

    $$$

    public double ne"t#umber() {

    %% put code li1e this in methods that use%modi'y it i" (this '= gen) throw new Illegal&tateception(*not singleton*)+

    return Math$random()

    !

    !

  • 8/9/2019 Patterns Singleton Memento Flyweight

    26/35

    26

    Pattern: l!"eig#t

    a class that has only one instance for eachunique state

  • 8/9/2019 Patterns Singleton Memento Flyweight

    27/35

  • 8/9/2019 Patterns Singleton Memento Flyweight

    28/35

  • 8/9/2019 Patterns Singleton Memento Flyweight

    29/35

    29

    l!"eig#t an( Strings

    l!"eig#te( strings a+a Strings are !"eig#te( &! t#e compiler "#ere+er

    possi&le

    can &e !"eig#te( at runtime "it# t#e internmet#o(

    public class String2est { public static void main(String34 args) { String 'ly & .'ly.5 eight & .eight. String 'ly6 & .'ly.5 eight6 & .eight.

    System$out$println('ly && 'ly6) %% true System$out$println(eight && eight6) %% true

    String distinctString & 'ly 7 eight System$out$println(distinctString && .'lyeight.) %% 'alse

    String 'lyeight & ('ly 7 eight)$intern() System$out$println('lyeight && .'lyeight.) %% true !!

  • 8/9/2019 Patterns Singleton Memento Flyweight

    30/35

    30

    9mplementing a l!"eig#t

    !"eig#ting "or-s &est on immutable o&)ects immutable: cannot &e c#ange( once constructe(

    class pseu(o8co(e s-etc#:

    pu&lic class FlyweightedE static map or ta&le o' instances

    pri+ate constructor

    static met#o( to get an instance i' "e #a+e create( t#is t!pe o' instance &e'ore, get it 'rom

    map an( return it ot#er"ise, ma-e t#e ne" instance, store an( return it

    F

  • 8/9/2019 Patterns Singleton Memento Flyweight

    31/35

    31

    l!"eig#t seuence(iagram

  • 8/9/2019 Patterns Singleton Memento Flyweight

    32/35

    32

    9mplementing a l!"eig#t

    public class Flyweighted{

    Map or table o' instances

    private Flyweighted() {!

    public static synchroni0ed FlyweightedgetInstance(Ob+ect 1ey) {

    i' (8myInstances$contains(1ey)) {

    Flyweighted' & ne Flyweighted(1ey)

    myInstances$put(1ey5 ')

    return ' ! else

    return (Flyweighted)myInstances$get(1ey)

    !

    !

  • 8/9/2019 Patterns Singleton Memento Flyweight

    33/35

    33

    Class &e'ore !"eig#ting

    G class to &e !"eig#te(public class Point {

    private int "5 y

    public Point(int "5 int y) { this$" & " this$y & y

    !

    public int get9() { return this$" !

    public int get:() { return this$y !

    public String toString() {

    return .(. 7 this$" 7 .5 . 7 this$y 7 .).

    !

    !

  • 8/9/2019 Patterns Singleton Memento Flyweight

    34/35

    34

    Class a'ter !"eig#ting

    G class t#at #as &een !"eig#te(4public class Point {

    private static ,ap instances = new -ash,ap()+

    public static oint getInstance(int int y) {

    String 1ey & " 7 .5 . 7 y i' (instances$contains;ey(1ey)) %% re

  • 8/9/2019 Patterns Singleton Memento Flyweight

    35/35

    35

    *e'erences

    T#e a+a Tutorial: 9$ #ttp:)a+a=sun=com(ocs&oo-stutorialessentialio

    a+a GP9 pages #ttp:)a+a=sun=com)2se1=