欢迎来到天天文库
浏览记录
ID:51621354
大小:263.50 KB
页数:43页
时间:2020-03-26
《软件设计模式-体系结构-PPT讲稿 0-Software-Design-Patterns-20121030 Lec3 Singleton Pattern-Creational.ppt》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、Lecture3SingletonPattern(Creational)单例模式Yushan(Michael)Sun2012-10-23Contents1)TheConceptoftheSingletonPattern2)ExampleofUsingtheSingletonPattern3)TheSingletonPatterninMulti-threadProgrammingSingletonPattern(Creational)单例模式TheConceptoftheSingletonPatternTheConceptoftheSingletonPat
2、ternReallifeexamples:OnecountryhasonlyonepresidentAcompanyhasonlyonegeneralmanagerAhusbandhasonlyonewifeOnebankaccounthasonlyonecreditcard现实世界的单例的例子软件中的单例情况Insoftwaredesign,someclassesmayonlyhaveoneinstance,thatis,onecancreateonlyoneobjectforoneclassandonecannotcreatetwoobjects.A
3、systemmayhaveonlyoneglobalobjecttocoordinatethewholebehaviorofthesystem.Example:Inaserverprogram,theconfigurationinformationisputintoafile,whichisreadbyasingletonobject.OtherobjectscanusethissingletonobjecttogettheconfigurationinformationAcompanycanhavemanyprinters,butprintingman
4、agementsystemhasonlyoneprinttaskcontrolobject,whichmanagesprintqueueanddistributestaskstoprintersTheWindowssystemhasonlyonefilesystemandawindowmanager.TheConceptoftheSingletonPattern怎样确保某个类仅仅能生成一个唯一的实例?Therearetwowaystoguaranteethatoneclasshasonlyoneinstanceandthisinstancecanbeea
5、silyobtained方法1:Onewayisthataprogrammerusescodeinaprogramtomakesurethatonlyoneobjectofaparticularclassbecreated;方法2:TheothermethodiscarefullydesignthestructureofaclassthatallowsonlyoneuniqueinstanceiscreatedtomakesureonlyoneobjectcanbecreatedTheConceptoftheSingletonPatternClientC
6、lassSingletonClass只能被创建一个唯一实例的类客户类方法1:在客户类中使用代码确保仅仅有一个SingletonClass的对象被创建方法2:精心设计SingletonClass类,使得仅仅唯一的一个该类的对象能被创建TheConceptoftheSingletonPattern第一种方法不好,因为程序员是很可能疏忽,而导致第二个实例被创建。第二种方法是从根本上保证仅仅有一个实例被创建的有效方法。这就是本节所讲述的实例模式所要表述的内容。TheConceptoftheSingletonPatternTheintentofthesinglet
7、onpattern:toguaranteethatoneclasshasonlyauniqueinstanceandprovideaglobalaccesspointforit.实现单例模式的思想:Inordertopreventclientprogramfromusingtheconstructortocreatemultipleobjects,theconstructorcanbeclaimedasprivatesothenoclientprogramcanuseittocreateanyobject问题:Iftheconstructorisclai
8、medasprivatetypethennoclientprogramcanus
此文档下载收益归作者所有