1. 程式人生 > >java學習之三種常用設計模式

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() ;
	}
};