以前走馬觀花的看了一遍設計模式,僅僅有了一個大致的瞭解,最近閒來無事,又重新開始看,突然發現工廠模式和策略模式理解起來感覺概念很模糊,故整理如下:
首先,我們來看簡單工廠模式
interface Fruit1{
public void result( );
}
/*
* 以下類均實現了接口
* 每次執行其實現的方法大多一樣
*/
class Apple1 implements Fruit1{
public void result( ) {
System.out.println("吃蘋果!");
}
}
class Orange1 implements Fruit1{
public void result( ) {
System.out.println("吃橘子!");
}
}
class Banana1 implements Fruit1{
public void result( ) {
System.out.print("吃個香蕉!");
}
}
/*
* 根據客戶端的輸入,生成相應的對象
*/
class factory {
public static Fruit1 getFruit(int kind){
Fruit1 fruit = null;
switch (kind){
case 0:
Apple1 apple = new Apple1();
fruit=apple;
break;
case 1:
Orange1 orange = new Orange1();
fruit=orange;
break;
case -1:
Banana1 banana = new Banana1();
fruit=banana;
break;
}
return fruit;
}
}
public class Factorytest {
public static void main(String[] args) {
// TODO Auto-generated method stub
Fruit1 f1;
f1 = factory.getFruit(0);
f1.result();
}
}
以下是策略模式和工廠模式的結合
/*
* 現在發生了變化,客戶端不僅僅再是簡單的“吃”水果了,而是由客戶端決定“吃”幾個
* 接口,定義了Eat()
*/
interface Fruit{
public void result(int num);
}
/*
* 以下類均實現了接口
* 其實現的方法每次執行的結果大多不一樣,要取決於客戶端的輸入
*/
class Apple implements Fruit{
public void result(int num) {
System.out.println("吃"+num+"個蘋果!");
}
}
class Orange implements Fruit{
public void result(int num) {
System.out.println("吃"+num+"個橘子!");
}
}
class Banana implements Fruit{
public void result(int num) {
System.out.print("吃"+num+"個香蕉!");
}
}
/*
* 策咯模式
*/
class countext {
Fruit fruit = null;
/*
* 根據客戶端的輸入,生成相應的對象
*/
public countext(int kind){
switch (kind){
case 0:
Apple apple = new Apple();
fruit=apple;
break;
case 1:
Orange orange = new Orange();
fruit=orange;
break;
case -1:
Banana banana = new Banana();
fruit=banana;
break;
}
}
public void getresult(int num){
fruit.result(num);
}
}
/*
* 客戶端
*/
public class Factory{
public static void main(String args[]){
/*
*客戶端只需要知道策略模式的Context對象
*/
countext con = new countext(0);
con.getresult(3);
}
}
由上述所得
策略模式與工廠模式的區別在於
1.策略模式封裝了變化,變化不會影響到客戶端
2.在策咯模式中,客戶端只需“知道”一個類,降低了耦合度