菜鳥譯文(二)——使用Java泛型構造模板方法模式,java模板

來源:互聯網
上載者:User

菜鳥譯文(二)——使用Java泛型構造模板方法模式,java模板

如果你發現你有很多重複的代碼,你可能會考慮用模板方法消除容易出錯的重複代碼。這裡有一個例子:下面的兩個類,完成了幾乎相同的功能:


正如你看到的,只有有注釋的地方是不一樣的。其他所有步驟都是相同的。


ProductCsvReader.java

public class ProductCsvReader {     Set<Product> getAll(File file) throws IOException {        Set<Product> returnSet = new HashSet<>();        try (BufferedReader reader = new BufferedReader(new FileReader(file))){            String line = reader.readLine();            while (line != null && !line.trim().equals("")) {                String[] tokens = line.split("\\s*,\\s*");                //不同                Product product = new Product(Integer.parseInt(tokens[0]), tokens[1], new BigDecimal(tokens[2]));                returnSet.add(product);                line = reader.readLine();            }        }        return returnSet;    }}

CustomerCsvReader.java
public class CustomerCsvReader {     Set<Customer> getAll(File file) throws IOException {        Set<Customer> returnSet = new HashSet<>();        try (BufferedReader reader = new BufferedReader(new FileReader(file))){            String line = reader.readLine();            while (line != null && !line.trim().equals("")) {                String[] tokens = line.split("\\s*,\\s*");                //不同                Customer customer = new Customer(Integer.parseInt(tokens[0]), tokens[1], tokens[2], tokens[3]);                returnSet.add(customer);                line = reader.readLine();            }        }        return returnSet;    }}

對於本例來說,只有兩個實體,但是一個真正的系統可能有幾十個實體,所以有很多重複易錯的代碼。你可能會發現Dao層有著相同的情況,在每個Dao進行增刪改查的時候幾乎都是相同的操作,唯一與不同的是實體和表。讓我們重構這些煩人的代碼吧。根據GoF設計模式第一部分提到的原則之一,我們應該“封裝不同的概念“ProductCsvReader和CustomerCsvReader之間,不同的是有注釋的代碼。所以我們要做的是,把相同的放到一個類,不同的抽取到另一個類。我們先開始編寫ProductCsvReader,我們使用Extract Method提取帶注釋的部分:


ProductCsvReader.java after Extract Method
public class ProductCsvReader {     Set<Product> getAll(File file) throws IOException {        Set<Product> returnSet = new HashSet<>();        try (BufferedReader reader = new BufferedReader(new FileReader(file))){            String line = reader.readLine();            while (line != null && !line.trim().equals("")) {                String[] tokens = line.split("\\s*,\\s*");                Product product = unmarshall(tokens);                returnSet.add(product);                line = reader.readLine();            }        }        return returnSet;    }    Product unmarshall(String[] tokens) {        Product product = new Product(Integer.parseInt(tokens[0]), tokens[1],                 new BigDecimal(tokens[2]));        return product;    }}

現在我們已經把相同(重複)的代碼和不同(各自特有)的代碼分開了,我們要建立一個父類AbstractCsvReader,它包括兩個類(ProductReader和CustomerReader)相同的部分。我們把它定義為一個抽象類別,因為我們不需要執行個體化它。然後我們將使用Pull Up Method重構這個父類。


AbstractCsvReader.java
abstract class AbstractCsvReader {    Set<Product> getAll(File file) throws IOException {        Set<Product> returnSet = new HashSet<>();        try (BufferedReader reader = new BufferedReader(new FileReader(file))){            String line = reader.readLine();            while (line != null && !line.trim().equals("")) {                String[] tokens = line.split("\\s*,\\s*");                Product product = unmarshall(tokens);                returnSet.add(product);                line = reader.readLine();            }        }        return returnSet;    }}

ProductCsvReader.java after Pull Up Method
public class ProductCsvReader extends AbstractCsvReader {    Product unmarshall(String[] tokens) {       Product product = new Product(Integer.parseInt(tokens[0]), tokens[1],                 new BigDecimal(tokens[2]));        return product;    }}

如果在子類中沒有‘unmarshall’方法,該類就無法進行編譯(它調用unmarshall方法),所以我們要建立一個叫unmarshall的抽象方法。


AbstractCsvReader.java with abstract unmarshall method
abstract class AbstractCsvReader {    Set<Product> getAll(File file) throws IOException {        Set<Product> returnSet = new HashSet<>();        try (BufferedReader reader = new BufferedReader(new FileReader(file))){            String line = reader.readLine();            while (line != null && !line.trim().equals("")) {                String[] tokens = line.split("\\s*,\\s*");                Product product = unmarshall(tokens);                returnSet.add(product);                line = reader.readLine();            }        }        return returnSet;    }    abstract Product unmarshall(String[] tokens);}

現在,在這一點上,AbstractCsvReader是ProductCsvReader的父類,但不是CustomerCsvReader的父類。如果CustomerCsvReader繼承AbstractCsvReader編譯會報錯。為瞭解決這個問題我們使用泛型。


AbstractCsvReader.java with Generics
abstract class AbstractCsvReader<T> {    Set<T> getAll(File file) throws IOException {        Set<T> returnSet = new HashSet<>();        try (BufferedReader reader = new BufferedReader(new FileReader(file))){            String line = reader.readLine();            while (line != null && !line.trim().equals("")) {                String[] tokens = line.split("\\s*,\\s*");                T element = unmarshall(tokens);                returnSet.add(product);                line = reader.readLine();            }        }        return returnSet;    }    abstract T unmarshall(String[] tokens);}

ProductCsvReader.java with Generics
public class ProductCsvReader extends AbstractCsvReader<Product> {    @Override    Product unmarshall(String[] tokens) {       Product product = new Product(Integer.parseInt(tokens[0]), tokens[1],                 new BigDecimal(tokens[2]));        return product;    }}

CustomerCsvReader.java with Generics
public class CustomerCsvReader extends AbstractCsvReader<Customer> {    @Override    Customer unmarshall(String[] tokens) {        Customer customer = new Customer(Integer.parseInt(tokens[0]), tokens[1],                 tokens[2], tokens[3]);        return customer;    }}

這就是我們要的!不再有重複的代碼!父類中的方法是“模板”,它包含這不變的代碼。那些變化的東西作為抽象方法,在子類中實現。記住,當你重構的時候,你應該有自動化的單元測試來保證你不會破壞你的代碼。我使用JUnit,你可以使用我帖在這裡的代碼,也可以在這個Github庫找一些其他設計模式的例子。在結束之前,我想說一下模板方法的缺點。模板方法依賴於繼承,患有 the Fragile Base Class Problem。簡單的說就是,修改父類會對繼承它的子類造成意想不到的不良影響。事實上,基礎設計原則之一的GoF設計模式提倡“多用組合少用繼承”,並且許多其他設計模式也告訴你如何避免代碼重複,同時又讓複雜或容易出錯的代碼盡量少的依賴繼承。歡迎交流,以便我可以提高我的部落格品質。


原文地址;Template Method Pattern Example Using Java Generics


翻譯的不好,歡迎拍磚!




Java泛型集合的應用與方法

定義一個泛型類
import java.util.*;
/**
* Description:
* <br/>Copyright (C), 2005-2008, Yeeku.H.Lee
* <br/>This program is protected by copyright laws.
* <br/>Program Name:
* <br/>Date:
* @author Yeeku.H.Lee kongyeeku@163.com
* @version 1.0
*/
//定義Apple類時使用了泛型聲明
public class Apple<T>
{
//使用T類型形參定義屬性
private T info;

public Apple(){}
//下面方法中使用T類型形參來定義方法
public Apple(T info)
{
this.info = info;
}
public void setInfo(T info)
{
this.info = info;
}
public T getInfo()
{
return this.info;
}
public static void main(String[] args)
{
//因為傳給T形參的是String實際類型,所以構造器的參數只能是String
Apple<String> a1 = new Apple<String>("蘋果");
System.out.println(a1.getInfo());
//因為傳給T形參的是Double實際類型,所以構造器的參數只能是Double或者double
Apple<Double> a2 = new Apple<Double>(5.67);
System.out.println(a2.getInfo());
}
}

泛型的作用:
比如說List 集合類,List 可以放進各種資料,那麼怎樣才能讓系統知道List 存的是什麼類型的資料呢? 這時就需要使用泛型,比如 List<String> listString =new ArrayList<String>();這樣就可以指定listString存的是String類型的資料。

泛型的內容有很多,推薦一本書 李剛的 瘋狂java講義,我自己也是用這本書學習的。
 
java 方法中怎在傳回型別使用泛型

這樣不能啊!
List<Integer>和List<String>是不同的傳回型別!
你倒是可以返回List<Object>但是後期用的話要cast!
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.