Posted By

kolepep on 02/17/16



Versions (?)

Traits pattern

 / Published in: Java


Traits both provide a set of methods that implement behaviour to a class and require that the class implement a set of methods that parameterize the provided behaviour. A trait is kind of a “micro interface” that describes some characteristic of a class design that can be found in many different components throughout the system. By referring to the traits instead of the implementing class itself you can keep the system decoupled and modular.

  1. public interface HasComments<R extends HasComments<R>> {
  2. // one method that parameterize the provided behaviour
  3. List<Comment> getComments();
  4. // two methods that implement the behaviour
  5. default R add(Comment comment) {
  6. getComments().add(comment);
  7. return (R) this;
  8. }
  9. default R remove(Comment comment) {
  10. getComments().remove(comment);
  11. return (R) this;
  12. }
  13. }

Report this snippet  

You need to login to post a comment.