在Android中用得最多的设计模式或许就是代理模式了
看懂下面代码,代理模式就入门了
package org. proxy. test;
public class Main {
public static void main ( String[ ] args) {
Object object = new ProxyObject ( ) ;
object. action ( ) ;
}
interface Object {
void action ( ) ;
}
static class ObjectImpl implements Object {
@Override
public void action ( ) {
System. out. println ( "=========================" ) ;
System. out. println ( "ObjectImpl" ) ;
System. out. println ( "=========================" ) ;
}
}
static class ProxyObject implements Object {
Object object;
public ProxyObject ( ) {
object = new ObjectImpl ( ) ;
}
@Override
public void action ( ) {
System. out. println ( "ProxyObject代理开始" ) ;
object. action ( ) ;
System. out. println ( "ProxyObject代理结束" ) ;
}
}
}
package org. proxy. test;
public class Main {
public static void main ( String[ ] args) {
Object object = new ProxyObject ( ) ;
object. action ( ) ;
}
static abstract class Object {
abstract void action ( ) ;
}
static class ObjectImpl extends Object {
@Override
public void action ( ) {
System. out. println ( "=========================" ) ;
System. out. println ( "ObjectImpl" ) ;
System. out. println ( "=========================" ) ;
}
}
static class ProxyObject extends Object {
Object object;
public ProxyObject ( ) {
object = new ObjectImpl ( ) ;
}
@Override
public void action ( ) {
System. out. println ( "ProxyObject代理开始" ) ;
object. action ( ) ;
System. out. println ( "ProxyObject代理结束" ) ;
}
}
}
练习一下
package org. proxy;
public class Main {
public static void main ( String[ ] args) {
Context context = new ContextImpl ( ) ;
Context proxy = new ProxyContext ( ( ContextImpl) context) ;
proxy. action ( ) ;
}
static abstract class Context {
abstract void action ( ) ;
}
static class ContextImpl extends Context {
@Override
void action ( ) {
System. out. println ( "我是实际实现" ) ;
}
}
static class ProxyContext extends Context {
ContextImpl context;
public ProxyContext ( ContextImpl context) {
this . context = context;
}
@Override
void action ( ) {
System. out. println ( "被Hook了" ) ;
context. action ( ) ;
}
}
}