泛型的使用保证返回的对象类型的正确;
package com.stono.gentest; import java.util.ArrayList; import java.util.List; public class StoryTeller { public static void main(String[] args) { List<Minstrel> story = StoryTemplate.getStory("select", new StoryI<Minstrel>() { @Override public Minstrel getHero(String name) { return new Minstrel(name); } }, 1); for (Minstrel minstrel : story) { System.out.println(minstrel.getName()); } } } class Minstrel { private String name; public Minstrel(String name) { this.name = name; } public String getName() { return name; } } // ==================下面为伪框架部分,以上为伪客户部分;===================== // 模版方法按照接口的规则进行泛型对象的创建;按照条件进行组装的逻辑不需要客户端写; class StoryTemplate { public static <T> List<T> getStory(String str, StoryI<T> t, Object... o) { List<T> list = new ArrayList<T>(); if ("select".equals(str)) {// 类似于jdbc的查询方法; String[] strs = { "a", "b" }; for (String string : strs) { list.add(t.getHero(string)); } } return list; } } interface StoryI<T> { T getHero(String name);// 传入一个参数String,保证返回一个泛型对象,组装逻辑由客户端实现; }
时间: 2024-10-11 08:48:55