我要去尝试我最好的解释。
我用的播放框架2,我会做很多CRUD操作。 他们中有些人会identitcal,所以我想吻和DRY所以起初我在想一个抽象类,包含list
, details
, create
, update
和delete
方法,与通用对象,并通过指定扩展这个类对象使用(型号和表单):
public abstract class CrudController extends Controller {
protected static Model.Finder<Long, Model> finder = null;
protected static Form<Model> form = null;
public static Result list() {
// some code here
}
public static Result details(Long id) {
// some code here
}
public static Result create() {
// some code here
}
public static Result update(Long id) {
// some code here
}
public static Result delete(Long id) {
// some code here
}
}
而一个类,将使用CRUD:
public class Cities extends CrudController {
protected static Model.Finder<Long, City> finder = City.find;
protected static Form<City> form = form(City.class);
// I can override a method in order to change it's behavior :
public static Result list() {
// some different code here, like adding some where condition
}
}
如果我在一个静态的背景是不是这会工作。
但由于它的话,我该怎么办?
这可以使用委托来实现:定义包含CRUD操作逻辑常规的Java类:
public class Crud<T extends Model> {
private final Model.Finder<Long, T> find;
private final Form<T> form;
public Crud(Model.Finder<Long, T> find, Form<T> form) {
this.find = find;
this.form = form;
}
public Result list() {
return ok(Json.toJson(find.all()));
}
public Result create() {
Form<T> createForm = form.bindFromRequest();
if (createForm.hasErrors()) {
return badRequest();
} else {
createForm.get().save();
return ok();
}
}
public Result read(Long id) {
T t = find.byId(id);
if (t == null) {
return notFound();
}
return ok(Json.toJson(t));
}
// … same for update and delete
}
然后,定义具有包含的实例的静态字段一个播放控制器Crud<City>
:
public class Cities extends Controller {
public final static Crud<City> crud = new Crud<City>(City.find, form(City.class));
}
而你几乎完成:你只需要定义渣滓的行动路线:
GET / controllers.Cities.crud.list()
POST / controllers.Cities.crud.create()
GET /:id controllers.Cities.crud.read(id: Long)
注意:这个例子中产生JSON响应为brevety但它可能使HTML模板。 然而,由于播放2模板是静态类型你需要所有这些传递的参数Crud
类。
(免责声明:我有playframework没有经验。)
下面的想法可能会有所帮助:
public interface IOpImplementation {
public static Result list();
public static Result details(Long id);
public static Result create();
public static Result update(Long id);
public static Result delete(Long id);
}
public abstract class CrudController extends Controller {
protected static Model.Finder<Long, Model> finder = null;
protected static Form<Model> form = null;
protected static IOpImplementation impl;
public static Result list() {
return impl.list();
}
public static Result details(Long id) {
return impl.details(id);
}
// other operations defined the same way
}
public class Cities extends CrudController {
public static Cities() {
impl = new CitiesImpl();
}
}
这样你就可以创建实现的层次结构。
(这必须是一些奇特的命名设计模式,但我不知道名字ATM)。