How to use generic class with specific objects in a static context?

前端 未结 2 939
难免孤独
难免孤独 2020-12-25 08:30

I\'m gonna try to explain at my best.

I use Play Framework 2, and I will do a lot of CRUD actions. Some of them will be identitcal, so I\'d like to KISS and DRY so a

2条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-25 09:17

    This can be achieved using delegation: define a regular Java class containing the CRUD actions logic:

    public class Crud {
    
        private final Model.Finder find;
        private final Form form;
    
        public Crud(Model.Finder find, Form form) {
            this.find = find;
            this.form = form;
        }
    
        public Result list() {
            return ok(Json.toJson(find.all()));
        }
    
        public Result create() {
            Form 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
    }
    

    Then you can define a Play controller having a static field containing an instance of Crud:

    public class Cities extends Controller {
        public final static Crud crud = new Crud(City.find, form(City.class));
    }
    

    And you’re almost done: you just need to define the routes for the Crud actions:

    GET     /                     controllers.Cities.crud.list()
    POST    /                     controllers.Cities.crud.create()
    GET     /:id                  controllers.Cities.crud.read(id: Long)
    

    Note: this example produces JSON responses for brevety but it’s possible to render HTML templates. However, since Play 2 templates are statically typed you’ll need to pass all of them as parameters of the Crud class.

提交回复
热议问题