Read Sean

Read me, read Sean.
posts - 508, comments - 655, trackbacks - 9, articles - 4

[Jakarta Commons筆記] Commons Collections - Transformer組

Posted on 2005-08-06 10:40 laogao 閱讀(2483) 評論(1)  編輯  收藏 所屬分類: On Java

 

接下來看Transformer組。

 

Transformer

ChainedTransformer

SwitchTransformer

TransformerUtils

 

我們有時候需要將某個對象轉換成另一個對象供另一組方法調用,而這兩類對象的類型有可能并不是出于同一個繼承體系的,或者說出了很基本的Object之外沒有共同的父類,或者我們根本不關心他們是不是有其他繼承關系,甚至就是同一個類的實例只是對我們而言無所謂,我們為了它能夠被后續的調用者有意義的識別和處理,在這樣的情形,我們就可以利用Transformer。除了基本的轉型Transformer之外,Commons Collections還提供了Transformer鏈和帶條件的Transformer,使得我們很方便的組裝出有意義的轉型邏輯。

 

假定我們在處理員工聘用時,需要將原來的Applicant對象轉換為Employee對象,而Applicant類和Employee類無論繼承關系、字段內容、具體業務職能等等都不是同一派系的,只是某些字段是相關的,且要求必要的轉換,那么這個時候我們使用Transformer就可以比較方便的實現這項功能,并且由于它的實現是靈活的、模塊化的,使得今后的維護也變得清晰和易于處理。代碼如下:

 

/** Applicant.java */

 

package sean.study.commons.collections;

 

import org.apache.commons.lang.builder.ToStringBuilder;

import org.apache.commons.lang.builder.ToStringStyle;

 

public class Applicant {

   

    private String name;

    private int age;

    private String applyFor;

   

    public Applicant() {

    }

 

    public Applicant(String name, int age, String applyFor) {

        this.name = name;

        this.age = age;

        this.applyFor = applyFor;

    }

   

    public String toString() {

        return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE)

                .append("name", name)

                .append("age", age)

                .append("applyFor", applyFor)

                .toString();

    }

 

    public int getAge() {

        return age;

    }

 

    public void setAge(int age) {

        this.age = age;

    }

 

    public String getApplyFor() {

        return applyFor;

    }

 

    public void setApplyFor(String applyFor) {

        this.applyFor = applyFor;

    }

 

    public String getName() {

        return name;

    }

 

    public void setName(String name) {

        this.name = name;

    }

 

}

 

/** Employee.java */

 

package sean.study.commons.collections;

 

import java.util.Date;

 

import org.apache.commons.lang.builder.ToStringBuilder;

import org.apache.commons.lang.builder.ToStringStyle;

import org.apache.commons.lang.time.DateFormatUtils;

 

public class Employee {

 

    private String name;

    private int age;

    private Date dateJoined;

    private String grade;

    private double salary;

   

    public Employee() {

    }

 

    public Employee(String name, int age, Date dateJoined, String grade, double salary) {

        this.name = name;

        this.age = age;

        this.dateJoined = dateJoined;

        this.grade = grade;

        this.salary = salary;

    }

   

    public String toString() {

        return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE)

                .append("name", name)

                .append("age", age)

                .append("dateJoined", DateFormatUtils.format(dateJoined, "yyyy-MM-dd"))

                .append("grade", grade)

                .append("salary", salary)

                .toString();

    }

 

    public int getAge() {

        return age;

    }

 

    public void setAge(int age) {

        this.age = age;

    }

 

    public Date getDateJoined() {

        return dateJoined;

    }

 

    public void setDateJoined(Date dateJoined) {

        this.dateJoined = dateJoined;

    }

 

    public String getGrade() {

        return grade;

    }

 

    public void setGrade(String grade) {

        this.grade = grade;

    }

 

    public String getName() {

        return name;

    }

 

    public void setName(String name) {

        this.name = name;

    }

 

    public double getSalary() {

        return salary;

    }

 

    public void setSalary(double salary) {

        this.salary = salary;

    }

 

}

 

/** TransformerUsage.java */

 

package sean.study.commons.collections;

 

import java.util.Arrays;

import java.util.Collection;

import java.util.Date;

import java.util.Iterator;

import java.util.List;

 

import org.apache.commons.collections.CollectionUtils;

import org.apache.commons.collections.Predicate;

import org.apache.commons.collections.Transformer;

import org.apache.commons.collections.functors.SwitchTransformer;

import org.apache.commons.lang.StringUtils;

 

public class TransformerUsage {

 

    public static void main(String[] args) {

        demoTransformerUsage();

    }

   

    public static void demoTransformerUsage() {

 

        System.out.println(StringUtils.center(" demoTransformerUsage ", 40, "="));

 

        // data setup

        Applicant[] applicants = new Applicant[] {

            new Applicant("Tony", 26, "Developer"),

            new Applicant("Michelle", 24, "Tester"),

            new Applicant("Jack", 28, "Project Manager")

        };

        List appList = Arrays.asList(applicants);

       

        // predicate setup

        Predicate isDeveloper = new Predicate() {

            public boolean evaluate(Object obj) {

                Applicant app = (Applicant) obj;

                return "Developer".equalsIgnoreCase(app.getApplyFor());

            }

        };

        Predicate isTester = new Predicate() {

            public boolean evaluate(Object obj) {

                Applicant app = (Applicant) obj;

                return "Tester".equalsIgnoreCase(app.getApplyFor());

            }

        };

        Predicate isPM = new Predicate() {

            public boolean evaluate(Object obj) {

                Applicant app = (Applicant) obj;

                return "Project Manager".equalsIgnoreCase(app.getApplyFor());

            }

        };

        Predicate[] checkApplyFor = new Predicate[] {

            isDeveloper,

            isTester,

            isPM

        };

       

        // transformer setup

        Transformer developerTransformer = new Transformer() {

            public Object transform(Object obj) {

                Applicant app = (Applicant) obj;

                return new Employee(

                    app.getName(), app.getAge(), new Date(), "E4", 2000

                );

            }

        };

        Transformer testerTransformer = new Transformer() {

            public Object transform(Object obj) {

                Applicant app = (Applicant) obj;

                return new Employee(

                    app.getName(), app.getAge(), new Date(), "E4", 2000

                );

            }

        };

        Transformer pmTransformer = new Transformer() {

            public Object transform(Object obj) {

                Applicant app = (Applicant) obj;

                return new Employee(

                    app.getName(), app.getAge(), new Date(), "E5", 3000

                );

            }

        };

        Transformer[] transformers = new Transformer[] {

            developerTransformer,

            testerTransformer,

            pmTransformer

        };

       

        // transform

        Transformer employTransformer = new SwitchTransformer(

            checkApplyFor, transformers, null

        );

        Collection employed = CollectionUtils.collect(appList, employTransformer);

       

        // output

        System.out.println("Applicants: ");

        Iterator iter1 = appList.iterator();

        while (iter1.hasNext()) {

            System.out.println(iter1.next());

        }

        System.out.println("Employed: ");

        Iterator iter2 = employed.iterator();

        while (iter2.hasNext()) {

            System.out.println(iter2.next());

        }

 

        System.out.println(StringUtils.repeat("=", 40));

    }

 

}

 

以下是運行結果:

 

========= demoTransformerUsage =========

Applicants:

Applicant[name=Tony,age=26,applyFor=Developer]

Applicant[name=Michelle,age=24,applyFor=Tester]

Applicant[name=Jack,age=28,applyFor=Project Manager]

Employed:

Employee[name=Tony,age=26,dateJoined=2005-08-05,grade=E4,salary=2000.0]

Employee[name=Michelle,age=24,dateJoined=2005-08-05,grade=E4,salary=2000.0]

Employee[name=Jack,age=28,dateJoined=2005-08-05,grade=E5,salary=3000.0]

========================================

 

我們首先定義一組Predicate,用于在SwitchTransformer中判斷采用那個具體的Transformer,這個具體的Transformer也是通過數組同時傳遞給SwitchTransformer的構造方法的。不同的Predicate可以有不同的實現,不同的Transformer也可以有不同的實現,因為它們之間實際上完全是相互獨立的。這就使我們有效的分離了邏輯和具體業務。

 

 

Feedback

# re: [Jakarta Commons筆記] Commons Collections - Transformer組  回復  更多評論   

2006-12-10 00:25 by
言簡意賅,非常清楚

只有注冊用戶登錄后才能發表評論。


網站導航:
 
云南11选5软件