java学习之三种常用设计模式

一、适配器设计模式

简单来说,就是通过一个间接类来选择性的来覆写一个接口

interface Window{
	public void open() ;	// 打开窗口
	public void close() ;	// 关闭窗口
	public void icon() ;	// 最小化
	public void unicon() ;	// 最大化
}
abstract class WindowAdapter implements Window{
	public void open(){}
	public void close(){}
	public void icon(){}
	public void unicon(){}
};
class MyWindow extends WindowAdapter{
	public void open(){
		System.out.println("打开窗口!") ;
	}
};
public class AdpaterDemo{
	public static void main(String args[]){
		Window win = new MyWindow() ;
		win.open() ;
	}
}

二、工厂设计模式

设计一个选择吃橘子或者苹果的例子,一般设计时可能会直接在主类中实例化对象,但通过工厂设计模式通过一个间接类可以减少主类中(客户端)的代码量

interface Fruit{
	public void eat() ;
}
class Apple implements Fruit{
	public void eat(){
		System.out.println("吃苹果。。。") ;
	}
};
class Orange implements Fruit{
	public void eat(){
		System.out.println("吃橘子。。。") ;
	}
};
class Factory{	// 工厂类
	public static Fruit getFruit(String className){
		Fruit f = null ;
		if("apple".equals(className)){
			f = new Apple() ;
		}
		if("orange".equals(className)){
			f = new Orange() ;
		}
		return f ;
	}
};
public class InterDemo{
	public static void main(String args[]){
		Fruit f = Factory.getFruit(args[0]) ;
		if(f!=null){
			f.eat() ;
		}
	}
}

三、代理设计模式

以讨债为例

interface Give{
	public void giveMoney() ;
}
class RealGive implements Give{
	public void giveMoney(){
		System.out.println("把钱还给我。。。。。") ;
	}
};
class ProxyGive implements Give{	// 代理公司
	private Give give = null ;
	public ProxyGive(Give give){
		this.give = give ;
	}
	public void before(){
		System.out.println("准备:小刀、绳索、钢筋、钢据、手枪、毒品") ;
	}
	public void giveMoney(){
		this.before() ;
		this.give.giveMoney() ;	// 代表真正的讨债者完成讨债的操作
		this.after() ;
	}
	public void after(){
		System.out.println("销毁所有罪证") ;
	}
};
public class ProxyDemo{
	public static void main(String args[]){
		Give give = new ProxyGive(new RealGive()) ;
		give.giveMoney() ;
	}
};


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值