设计模式(一)

5 篇文章 0 订阅
2 篇文章 0 订阅

设计模式

工厂模式

public class Test {
    public static void main(String[] args) {
        Computer c1 =ComputerFactory.createComputerInstance(); 
        c1.start();

        Computer c2=ComputerFactory.createComputerInstance(); 
        c2.start();

        System.out.println(c1==c2);  //false
    }
}

class ComputerFactory {
    public static  Computer createComputerInstance() {
        return new Computer(16,"华为","华硕");
    }
}

class Computer{
    public Computer(int memory, String disk, String mainboard){
        this.memory = memory;
        this.disk = disk;
        this.mainboard = mainboard;
    }

    int memory;
    String disk;
    String mainboard;

    void start() {
        System.out.println("... 电脑自检....");
        System.out.println("内存:"+ memory );
        System.out.println("硬盘:"+ disk );
        System.out.println("主板:"+ mainboard );
        System.out.println("电脑正常运行 ...");
    }	
}

特点:
1) 创建出来的对象,每次得到的都是一个新的实例
2) 把应用和对象的创建过程解耦合, 提升程序的可维护性和可扩展性

代理模式

ProxyFactory.java

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

//代理工厂,用来生成代理类对象
public class ProxyFactory implements InvocationHandler{
	//委托对象
    private Object targetObj;
    
	//用这个方法创建代理对象
    //this.targetObj.getClass() 得到目标对象的类装载器
	//this.targetObj.getClass().getInterfaces() 得到目标对象实现的接口
	//this 是一个实现了InvocationHandler 的类对象
	public Object createProxyInstance(Object targetObj) {
		this.targetObj=targetObj;
		return Proxy.newProxyInstance(this.targetObj.getClass().getClassLoader(), this.targetObj.getClass().getInterfaces(), this);
	}
	
    //proxy 代理对象
	//method 代表拦到的方法
	//args 代表拦到的方法的参数
	//Object 类型的返回值,代表拦到的方法的返回值
	public Object invoke(Object proxy,Method method, Object[] args) throws Throwable{
		Object result = null;
		String methodName = method.getName();
		
		if(methodName.startsWith("play")) {
			System.out.println("电影马上开始了,爆米花、可乐、口香糖9.8折,快来买啊!");
			method.invoke(targetObj, args);
			System.out.println("电影马上结束了,爆米花、可乐、口香糖9.8折,买回家吃吧!");
		}
		
		return result;
	}

}
public interface Movie {
	void play();
}

public class RealMovie implements Movie {
	public void play() {
		System.out.println("正在播放喜羊羊与灰太狼");
	}
}

public static void main(String[] args) {
		Movie movie = (Movie) new ProxyFactory().createProxyInstance(new RealMovie());
		movie.play();
	}

}

要注意,用这样的方式创建代理对象,要求目标对象必须实现接口

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Abner-G-Zhang

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值