Posted By

kolepep on 02/17/16


Tagged

pattern


Versions (?)

Traits pattern


 / Published in: Java
 

URL: https://dzone.com/articles/definition-of-the-trait-pattern-in-java?utm_medium=feed&utm_source=feedpress.me&utm_campaign=Feed:%20dzone%2Fjava

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.