《Java与模式》重点总结04.docx
- 文档编号:11034804
- 上传时间:2023-02-24
- 格式:DOCX
- 页数:21
- 大小:303.46KB
《Java与模式》重点总结04.docx
《《Java与模式》重点总结04.docx》由会员分享,可在线阅读,更多相关《《Java与模式》重点总结04.docx(21页珍藏版)》请在冰豆网上搜索。
《Java与模式》重点总结04
八、代理(Proxy)模式
1、代理模式
(1)示例类图
(2)示例代码清单
/*
*创建日期2007-3-13
*
*TODO要更改此生成的文件的模板,请转至
*窗口-首选项-Java-代码样式-代码模板
*/
packagecom.langsin.proxy;
//抽象角色
abstractpublicclassSubject{
abstractpublicvoidrequest();
}
packagecom.langsin.proxy;
//真实角色:
实现了Subject的request()方法
publicclassRealSubjectextendsSubject{
publicRealSubject(){
}
publicvoidrequest(){
System.out.println("Fromrealsubject.");
}
}
packagecom.langsin.proxy;
//代理角色
publicclassProxySubjectextendsSubject{
privateRealSubjectrealSubject;//以真实角色作为代理角色的属性
publicProxySubject(){
}
publicvoidrequest()//该方法封装了真实对象的request方法
{
preRequest();
if(realSubject==null){
realSubject=newRealSubject();
}
realSubject.request();//此处执行真实对象的request方法
postRequest();
}
privatevoidpreRequest(){
//somethingyouwanttodobeforerequesting
}
privatevoidpostRequest(){
//somethingyouwanttodoafterrequesting
}
}
packagecom.langsin.proxy;
//客户端调用
publicclassClient{
publicstaticvoidmain(String[]args){
Subjectsub=newProxySubject();
sub.request();
}
}
2、动态代理模式
(1)示例类图
(2)示例代码清单
packagecom.langsin.dynamicproxy;
//抽象角色(之前是抽象类,此处应改为接口):
publicinterfaceSubject{
abstractpublicvoidrequest();
}
packagecom.langsin.dynamicproxy;
//具体角色
publicclassRealSubjectimplementsSubject{
publicRealSubject(){
}
publicvoidrequest(){
System.out.println("Fromrealsubject.");
}
}
packagecom.langsin.dynamicproxy;
importjava.lang.reflect.InvocationHandler;
importjava.lang.reflect.Method;
//代理处理器
/**
*该代理类的内部属性为Object类,实际使用时通过该类的构造函数DynamicSubject(Objectobj)对其赋值;
*此外,在该类还实现了invoke方法,该方法中的method.invoke(sub,args);
*其实就是调用被代理对象的将要被执行的方法,方法参数sub是实际的被代理对象,args为执行被代理对象相应操作所需的参数。
*通过动态代理类,我们可以在调用之前或之后执行一些相关操作
*/
publicclassDynamicSubjectimplementsInvocationHandler{
privateObjectsub;
publicDynamicSubject(){
}
publicDynamicSubject(Objectobj){
sub=obj;
}
publicObjectinvoke(Objectproxy,Methodmethod,Object[]args)
throwsThrowable{
System.out.println("beforecalling"+method);
Objectobject=method.invoke(sub,args);
System.out.println("aftercalling"+method);
returnobject;
}
}
packagecom.langsin.dynamicproxy;
importjava.lang.reflect.InvocationHandler;
importjava.lang.reflect.Proxy;
//客户端
publicclassClient{
staticpublicvoidmain(String[]args)throwsThrowable{
Subjectrs=newRealSubject();//在这里指定被代理类
InvocationHandlerds=newDynamicSubject(rs);
Class
>cls=rs.getClass();
//以下是一次性生成代理
Subjectsubject=(Subject)Proxy.newProxyInstance(
cls.getClassLoader(),cls.getInterfaces(),ds);
subject.request();
}
}
(3)其它示例类图
九、享元(Flyweight)模式
1、单纯享元模式
(1)示例类图
(2)示例代码清单
packagecom.javapatterns.flyweight.simple;
abstractpublicclassFlyweight{
abstractpublicvoidoperation(Stringstate);
}
packagecom.javapatterns.flyweight.simple;
publicclassConcreteFlyweightextendsFlyweight{
privateCharacterintrinsicState=null;
publicConcreteFlyweight(Characterstate){
this.intrinsicState=state;
}
publicvoidoperation(Stringstate){
System.out.print("\nIntrinsicState="+intrinsicState
+",ExtrinsicState="+state);
}
}
packagecom.javapatterns.flyweight.simple;
importjava.util.Map;
importjava.util.HashMap;
importjava.util.Iterator;
publicclassFlyweightFactory{
privateHashMapflies=newHashMap();
/**
*@linkaggregation
*@directed
*@clientRoleFlyweights
*/
privateFlyweightlnkFlyweight;
publicFlyweightFactory(){
}
publicsynchronizedFlyweightfactory(Characterstate){
if(flies.containsKey(state)){
return(Flyweight)flies.get(state);
}else{
Flyweightfly=newConcreteFlyweight(state);
flies.put(state,fly);
returnfly;
}
}
publicvoidcheckFlyweight(){
Flyweightfly;
inti=0;
System.out.println("\n==========checkFlyweight()=============");
for(Iteratorit=flies.entrySet().iterator();it.hasNext();){
Map.Entrye=(Map.Entry)it.next();
System.out.println("Item"+(++i)+":
"+e.getKey());
}
System.out.println("==========checkFlyweight()=============");
}
}
packagecom.javapatterns.flyweight.simple;
publicclassClient{
privatestaticFlyweightFactoryfactory;
staticpublicvoidmain(String[]args){
factory=newFlyweightFactory();
Flyweightfly=factory.factory(newCharacter('a'));
fly.operation("FirstCall");
fly=factory.factory(newCharacter('b'));
fly.operation("SecondCall");
fly=factory.factory(newCharacter('a'));
fly.operation("ThirdCall");
//intrinsicFlyweight
factory.checkFlyweight();
}
}
输出结果:
IntrinsicState=a,ExtrinsicState=FirstCall
IntrinsicState=b,ExtrinsicState=SecondCall
IntrinsicState=a,ExtrinsicState=ThirdCall
==========checkFlyweight()=============
Item1:
b
Item2:
a
==========checkFlyweight()=============
2、复合享元模式
(1)示例类图
(2)示例代码清单
packageposite;
abstractpublicclassFlyweight{
abstractpublicvoidoperation(Stringstate);
}
packageposite;
publicclassConcreteFlyweightextendsFlyweight{
privateCharacterintrinsicState=null;
publicConcreteFlyweight(Characterstate){
this.intrinsicState=state;
}
publicvoidoperation(Stringstate){
System.out.print("\nInternalState="+intrinsicState
+"ExtrinsicState="+state);
}
}
packageposite;
importjava.util.Map;
importjava.util.HashMap;
importjava.util.Iterator;
publicclassConcreteCompositeFlyweightextendsFlyweight{
privateHashMapflies=newHashMap(10);
/**
*@linkaggregation
*@directed
*@clientRoleComposite
*/
privateFlyweightflyweight;
publicConcreteCompositeFlyweight(){
}
publicvoidadd(Characterkey,Flyweightfly){
flies.put(key,fly);
}
publicvoidoperation(StringextrinsicState){
Flyweightfly=null;
for(Iteratorit=flies.entrySet().iterator();it.hasNext();){
Map.Entrye=(Map.Entry)it.next();
fly=(Flyweight)e.getValue();
fly.operation(extrinsicState);
}
}
}
packageposite;
importjava.util.Map;
importjava.util.HashMap;
importjava.util.Iterator;
publicclassFlyweightFactory{
privateHashMapflies=newHashMap();
/**
*@linkaggregation
*@directed
*@clientRoleFlyweights
*/
privateFlyweightlnkFlyweight;
publicFlyweightFactory(){
}
publicFlyweightfactory(StringcompositeState){
ConcreteCompositeFlyweightcompositeFly=newConcreteCompositeFlyweight();
intlength=compositeState.length();
Characterstate=null;
for(inti=0;i state=newCharacter(compositeState.charAt(i)); System.out.println("factory("+state+")"); compositeFly.add(state,this.factory(state)); } returncompositeFly; } publicFlyweightfactory(Characterstate){ if(flies.containsKey(state)){ return(Flyweight)flies.get(state); }else{ Flyweightfly=newConcreteFlyweight(state); flies.put(state,fly); returnfly; } } publicvoidcheckFlyweight(){ Flyweightfly; inti=0; System.out.println("\n==========checkFlyweight()============="); for(Iteratorit=flies.entrySet().iterator();it.hasNext();){ Map.Entrye=(Map.Entry)it.next(); System.out.println("Item"+(++i)+": "+e.getKey()); } System.out.println("\n==========checkFlyweight()============="); } } packageposite; publicclassClient{ privatestaticFlyweightFactoryfactory; publicstaticvoidmain(String[]args){ factory=newFlyweightFactory(); Flyweightfly; /* *fly=factory.factory(newCharacter('a'));fly.operation(); * *fly=factory.factory(newCharacter('b'));fly.operation(); * *fly=factory.factory(newCharacter('a'));fly.operation(); */ fly=factory.factory("abcb"); fly.operation("CompositeCall"); //intrinsicFlyweight factory.checkFlyweight(); } } 十、门面(Facade)模式 (1)示例类图 (2)示例代码清单 packagecom.javapatterns.facade.securityfacade; publicclassSecurityFacade{ privateCameracamera1,camera2; privateLightlight1,light2,light3; privateSensorsensor; privateAlarmalarm; publicSecurityFacade(){ camera1=newCamera(); camera2=newCamera(); light1=newLight(); light2=newLight(); light3=newLight(); sensor=newSensor(); alarm=newAlarm(); } publicvoidactivate(){ camera1.turnOn(); camera2.turnOn(); light1.turnOn(); light2.turnOn(); light3.turnOn(); sensor.activate(); alarm.activate(); } publicvoiddeactivate(){ camera1.turnOff(); camera2.turnOff(); light1.turnOff(); light2.turnOff(); light3.turnOff(); sensor.deactivate(); alarm.deactivate(); } } packagecom.javapatterns.facade.securityfacade; publicclassAlarm{ publicvoidactivate(){ System.out.println("Activatingthealarm."); } publicvoiddeactivate(){ System.out.println("Deactivatingthealarm."); } publicvoidring(){ System.out.println("Ringthealarm."); } publicvoidstopRing(){ System.out.println("Stopthealarm."); } } packagecom.javapatterns.facade.securityfacade; publicclassCamera{ publicvoidturnOn(){ System.out.println("Turningonthecamera."); } publicvoidturnOff(){ System.out.println("Turningoffthecamera."); } publicvoidrotate(intdegrees){ System.out.println("Rotatingthecameraby"+degrees+"degrees."); } } packagecom.javapatterns.facade.securityfacade; publicclassLight{ publicvoidturnOn(){ System.
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- Java与模式 Java 模式 重点 总结 04
![提示](https://static.bdocx.com/images/bang_tan.gif)