简体   繁体   中英

Port Static model methods like(find, all) to java Models

I was previously a rails developer and used to use rails models like this and all the useful methods like find , all , find_by_id etc used to automatically added to those classes.

class Article < ActiveRecord::Base
end

Now I develop for Android and was attempting to build a similar layer by making parent class like ActiveRecord::Base so that all my android models have similar methods.

I have been successful in porting methods like save and reload as they were instance methods and could directly come from parent to child, but I am confused about how to do it with static methods like these.

Can someone please explain how can I accomplish similar behavior in Android .

Just don't do this. The ActiveRecord pattern as first described by Martin Fowler has some serious concerns. It violates the single responsibility principle. The advantage of, that it's simple to use. The creators of rails have hidden all the ugly stuff with Ruby magic.

There is no magic in Java. Relying havily on static methods will make your code resistent to dependency injection. And DI is the only method in Java to achieve loose coupled, modular and testable code.

Just use the DAO Pattern aka DataMapper. You will be creating two separate objects. One for quering/persiting and one for the bare data processing( most of the time it will just hold the data)

  public Class Articles {

   protected Connection connection;

   public Article(Connection connection) { ... }

   public List<Article> findByTitle(String title) { .. }

   public Boolean save(Article article)


 }


 public Class Article {

 protected String title;
 protected String text; 

 public String getTitle() {...}
 public String getText() {...}

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM