How much repository interfaces must created in Repository Pattern? - java

Assume we have following classes:
public class User
{
//User Definitions Goes Here
}
public class Product
{
//Product Definitions Goes Here
}
public class Order
{
//Order Definitions Goes Here
}
Having above models, Should I Create only one repository like:
public interface IRepository
{
//IRepository Definition Goes Here
}
Or it is better to have multiple repository:
public interface IUserRepository
{
//IUserRepository Definition Goes Here
}
public interface IProductRepository
{
//IProductRepository Definition Goes Here
}
public interface IOrderRepository
{
//IOrderRepository Definition Goes Here
}
And what is each pros and cons?

There is no must . You create as many as the app needs.You could have a repository interface for each business object and a generic interface.
Something like
interface ICRUDRepo<T> //where T is always a Domain object
{
T get(GUid id);
void Add(T entity);
void Save(T entity);
}
//then it's best (for maintainability) to define a specific interface for each case
interface IProductsRepository:ICRUDRepo<Product>
{
//additional methods if needed by the domain use cases only
//this search the storage for Products matching a certain criteria,
// then returns a materialized collection of products
//which satisfy the given criteria
IEnumerable<Product> GetProducts(SelectByDate criteria);
}
It's all about having a clean and clear abstraction which will allow proper decoupling of the Domain from persistence.
The generic abstraction is there so that we save a few keystrokes and maybe to have some common extension methods. However using a common generic interface for these purposes doesn't really count as DRY

If you adopt the first approach, you avoid repeating yourself, satisfying DRY principles. But you break separation of concerns principles by lumping unconnected items in one interface and any implementing class.
If you adopt the second approach, you implement good separation of concerns, but risk repeating yourself, so breaking DRY principles.
One solution is a third way: do a mixture.
public interface IRepository<T>
{
IEnumerable<T> Query {get;}
void Add(TEntity entity);
void Delete(TEntity entity);
}
public interface IUserRepository : IRepository<IUser>;
public interface IProductRepository : IRepository<IProduct>;
public interface IOrderRepository : IRepository<IOrder>;
This approach then satisfies both principles.

Related

Does strategy always needs to be passed from the client code in Strategy Pattern?

I have below piece of code:
public interface SearchAlgo { public Items search(); }
public class FirstSearchAlgo implements SearchAlgo { public Items search() {...} }
public class SecondSearchAlgo implements SearchAlgo { public Items search() {...} }
I also have a factory to create instances of above concrete classes based on client's input. Below SearchAlgoFactory code is just for the context.
public class SearchAlgoFactory {
...
public SearchAlgo getSearchInstance(String arg) {
if (arg == "First") return new FirstSearchAlgo();
if (arg == "Second") return new SecondSearchAlgo();
}
}
Now, I have a class that takes input from client, get the Algo from Factory and executes it.
public class Manager{
public Items execute(String arg) {
SearchAlgo algo = SearchAlgoFactory.getSearchInstance(arg);
return algo.search();
}
}
Question:
I feel that I am using both Factory and Strategy pattern but I am not sure 'cause whatever examples I have seen they all have a Context class to execute the strategy and client provides the strategy which they want to use. So, is this a correct implementation of Strategy?
If it comes to implementing design patterns, it is much more important to understand what they do than to conform to some gold standard reference implementation. And it looks like you understand the strategy pattern.
The important thing about strategies is that the implementation is external to some client code (usually called the context) and that it can be changed at runtime. This can be done by letting the user provide the strategy object directly. However, introducing another level of indirection through your factory is just as viable. Your Manager class acts as the context you see in most UML diagrams.
So, yes. In my opinion, your code implements the strategy pattern.

java open closed principle for multiple services

Let's say I wanted to define an interface which represents a call to a remote service.
Both Services have different request and response
public interface ExecutesService<T,S> {
public T executeFirstService(S obj);
public T executeSecondService(S obj);
public T executeThirdService(S obj);
public T executeFourthService(S obj);
}
Now, let's see implementation
public class ServiceA implements ExecutesService<Response1,Request1>
{
public Response1 executeFirstService(Request1 obj)
{
//This service call should not be executed by this class
throw new UnsupportedOperationException("This method should not be called for this class");
}
public Response1 executeSecondService(Request1 obj)
{
//execute some service
}
public Response1 executeThirdService(Request1 obj)
{
//execute some service
}
public Response1 executeFourthService(Request1 obj)
{
//execute some service
}
}
public class ServiceB implements ExecutesService<Response2,Request2>
{
public Response1 executeFirstService(Request1 obj)
{
//execute some service
}
public Response1 executeSecondService(Request1 obj)
{
//This service call should not be executed by this class
throw new UnsupportedOperationException("This method should not be called for this class");
}
public Response1 executeThirdService(Request1 obj)
{
//This service call should not be executed by this class
throw new UnsupportedOperationException("This method should not be called for this class");
}
public Response1 executeFourthService(Request1 obj)
{
//execute some service
}
}
In a other class depending on some value in request I am creating instance of either ServiceA or ServiceB
I have questions regarding the above:
Is the use of a generic interface ExecutesService<T,S> good in the case where you want to provide subclasses which require different Request and Response.
How can I do the above better?
Basically, your current design violates open closed principle i.e., what if you wanted to add executeFifthService() method to ServiceA and ServiceB etc.. classes.
It is not a good idea to update all of your Service A, B, etc.. classes, in simple words, classes should be open for extension but closed for modification.
Rather, you can refer the below approach:
ExecutesService interface:
public interface ExecutesService<T,S> {
public T executeService(S obj);
}
ServiceA Class:
public class ServiceA implements ExecutesService<Response1,Request1> {
List<Class> supportedListOfServices = new ArrayList<>();
//load list of classnames supported by ServiceA during startup from properties
public Response1 executeService(Request1 request1, Service service) {
if(!list.contains(Service.class)) {
throw new UnsupportedOperationException("This method should
not be called for this class");
} else {
return service.execute(request1);
}
}
}
Similarly, you can implement ServiceB as well.
Service interface:
public interface Service<T,S> {
public T execute(S s);
}
FirstService class:
public class FirstService implements Service<Request1,Response1> {
public Response1 execute(Request1 req);
}
Similarly, you need to implement SecondService, ThirdService, etc.. as well.
So, in this approach, you are basically passing the Service (to be actually called, it could be FirstService or SecondService, etc..) at runtime and ServiceA validates whether it is in supportedListOfServices, if not throws an UnsupportedOperationException.
The important point here is that you don't need to update any of the existing services for adding new functionality (unlike your design where you need to add executeFifthService() in ServiceA, B, etc..), rather you need to add one more class called FifthService and pass it.
I would suggest you to create two different interfaces every of which is handling its own request and response types.
Of course you can develop an implementation with one generic interface handling all logic but it may make the code more complex and dirty from my point of view.
regards
It makes not really sense to have a interface if you know that for one case, most of methods of the interface are not supported and so should not be called by the client.
Why provide to the client an interface that could be error prone to use ?
I think that you should have two distinct API in your use case, that is, two classes (if interface is not required any longer) or two interfaces.
However, it doesn't mean that the two API cannot share a common interface ancestor if it makes sense for some processing where instances should be interchangeable as they rely on the same operation contract.
Is the use of a generic interace (ExecutesService) good in the case
where you want to provide subclasses which require different Request
and Response.
It is not classic class deriving but in some case it is desirable as
it allows to use a common interface for implementations that has some enough similar methods but don't use the same return type or parameter types in their signature :
public interface ExecutesService<T,S>
It allows to define a contract where the classic deriving cannot.
However, this way of implementing a class doesn't allow necessarily to program by interface as the declared type specifies a particular type :
ExecutesService<String, Integer> myVar = new ExecutesService<>();
cannot be interchanged with :
ExecutesService<Boolean, String> otherVar
like that myVar = otherVar.
I think that your question is a related problem to.
You manipulate implementations that have close enough methods but are not really the same behavior.
So, you finish to mix things from two concepts that have no relation between them.
By using classic inheriting (without generics), you would have probably introduced very fast distinct interfaces.
I guess it is not a good idea to implement interface and make possible to call unsupported methods. It is a sign, that you should split your interface into two or three, depending on concrete situation, in a such way, that each class implements all methods of the implemented interface.
In your case I would split the entire interface into three, using inheritance to avoid doubling. Please, see the example:
public interface ExecutesService<T, S> {
T executeFourthService(S obj);
}
public interface ExecutesServiceA<T, S> extends ExecutesService {
T executeSecondService(S obj);
T executeThirdService(S obj);
}
public interface ExecutesServiceB<T, S> extends ExecutesService {
T executeFirstService(S obj);
}
Please, also take into account that it is redundant to place public modifier in interface methods.
Hope this helps.

Java generic return type for a interface getter (<T> T get();)

I am working in the design of a SDK that will provide: basic definitions (interfaces), logging and transaction engine for different projects. Each project will be considered as a platform and will be developed as a different project using as basis the SDK; they has similarities but each implementation should be able to solve specific behaviors, however the basic definitions from the core SDK should solve most part of the problems. For example: HUUniversity or MITUniversity
So far I have almost all achieved for example: there is StudentManager interface that provide essential behavior for any implementation:
public interface StudentManager<T> extends Manager, Release {
int getCurrentStudent();
int getTotalStudent();
TransactionManager getStudentManager();
List<T> getStudent();
void addStudent(T participant);
T getStudent(String id);
T removeStudent(String id);
}
That way each platform implementation will be able to implement its own definition where basically extend from the basic definition provided within the SDK but the each implementation will be strongly typed and would be able to implement new behaviors:
public interface HUStudentManager extends StudentManager<HUStudent>, ParticipantListener {
List<HUStudentCommand> getCommands(String audioId);
HUStudent getParticipant(ListType list, String id);
HUStudent getParticipantByName(String name);
List<HUStudent> getParticipants(StudentState state);
List<HUStudent getParticipantsOnList(ListType list);
List<HUStudent> getParticipantsOnList(ListType list, Sort sort);
void addParticipantOnList(HUStudent participant, ListType listType, long epoch);
HUStudentCommand removeCommand(String id);
HUStudentCommand removeParticipantByName String name);
void saveCommand(HUStudentCommand command)
}
Implementation: the HU platform has its own definition of a StudentManager (HUStudentManager), and extend from the basis (defined on the SDK) since the SDK doesn't know about any HUStudent definition I added a generic param to it so each
public class HUStudentManagerImpl extends HU implements
HUStudentManager<HUStudent> {
#Override
public void addStudent(HUStudent student) {
if(Utils.isNull(m_students.putIfAbsent(student.getId(), participant))){
m_totalStudents.incrementAndGet();
getLogger().log(Keywords.DEBUG,"{0}The instance: {1} with the specified key: {2} has been added to the ConcurrentMap<String, HUStudents>", getData(), student.getClass().toString(), student.getId());
}else{
getLogger().log(Keywords.WARNING,"{0}The instance: {1} with the specified key: {2} already exists in the ConcurrentMap<String, HUStudents>", getData(), student.getClass().toString(), student.getId());
}
}
}
The sample above works fine and solve the problem where I leave to each developer use his own definitions for the specific platform which of course will extend from the basic definitions
But I wasn't able to figured out how let the developer to use his own definition for a single type within the interface definition ie:
public interface Student extends IManager, IRelease {
UUID getUUID();
String getId();
<T> T getSchedule();
<T> T getElapsedTime();
}
I pretend that the basic interface allows to each developer to use its own definition force them to implement a basic behavior or implement a new one but extending from the existing on the SDK:
public interface HUStudent extends Student {
HUClass getClass()
}
How can I implement this on the final HUStudentImpl class without get the compiler error in order to suppress the types. is that possible or should I shadowed the definitions in super class with the desire type
public interface HUStudentImpl extends HU, implements HUStudent {
//Type safety: The expression of type getSchedule() needs unchecked
//conversion to conform to HUSchedule
HUSchedule getSchedule(); //Def from Student interface at SDK
HUElapsedTime getElapsedTime(); //Def from Student interface at SDK
}
I cannot use parameter over the Student interface since each getter could be a different type.
Hope someone can enlighten me and point me in the right direction.
Thanks in advance, best regards.

Dao Registry refactoring

Using the generic dao pattern, I define the generic interface:
public interface GenericDao<T extends DataObject, ID extends Serializable> {
T save(T t);
void delete(ID id);
T findById(ID id);
Class<T> getPersistentClass();
}
I then implemented an default GenericDaoImpl implementation to perform these functions with the following constructor:
public GenericDaoImpl(Class<T> clazz) {
this.persistentClass = clazz;
DaoRegistry.getInstance().register(clazz, this);
}
The point of the DaoRegistry is to look up a Dao by the class associating to it. This allows me to extend GenericDaoImpl and overwrite methods for objects that requires special handling:
DaoRegistry.getInstance().getDao(someClass.getClass()).save(someClass);
While it works, there are a few things that I don't like about it:
DaoRegistry is an singleton
The logic of calling save is complicated
Is there a better way to do this?
Edit
I am not looking to debate whether Singleton is an anti-pattern or not.
First of all, what is your problem with DaoRegistry being singleton?
Anyway, you could have an abstract base class for your entities that'd implement save like this
public T save(){
DaoRegistry.getInstance().getDao(this.getClass()).save(this);
}
then you could simply call someEntity.save()
Or it may be more straightforward if the entity classes itself implemented the whole GenericDao interface (save, delete and find methods), so the contents of your GenericDaoImpl would be in the base class of your entities.
It could be better to use instance of DaoRegistry instead of static methods. It would make it more manageable for test configurations. You could implement it as
#Component("daoRegistry")
public class DaoRegistry {
#Autowired
private List<GenericDao> customDaos;
private GenericDao defaultDao = new GenericDaoImpl();
public <T> T getDao(Class<T> clazz) {
// search customDaos for matching clazz, return default dao otherwise
}
}
Also you could add save method to it and rename accordingly. All customised daos should be available as beans.

when to use the abstract factory pattern?

I want to know when we need to use the abstract factory pattern.
Here is an example,I want to know if it is necessary.
The UML
THe above is the abstract factory pattern, it is recommended by my classmate.
THe following is myown implemention. I do not think it is necessary to use the pattern.
And the following is some core codes:
package net;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
public class Test {
public static void main(String[] args) throws IOException, InstantiationException, IllegalAccessException, ClassNotFoundException {
DaoRepository dr=new DaoRepository();
AbstractDao dao=dr.findDao("sql");
dao.insert();
}
}
class DaoRepository {
Map<String, AbstractDao> daoMap=new HashMap<String, AbstractDao>();
public DaoRepository () throws IOException, InstantiationException, IllegalAccessException, ClassNotFoundException {
Properties p=new Properties();
p.load(DaoRepository.class.getResourceAsStream("Test.properties"));
initDaos(p);
}
public void initDaos(Properties p) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
String[] daoarray=p.getProperty("dao").split(",");
for(String dao:daoarray) {
AbstractDao ad=(AbstractDao)Class.forName(dao).newInstance();
daoMap.put(ad.getID(),ad);
}
}
public AbstractDao findDao(String id) {return daoMap.get(id);}
}
abstract class AbstractDao {
public abstract String getID();
public abstract void insert();
public abstract void update();
}
class SqlDao extends AbstractDao {
public SqlDao() {}
public String getID() {return "sql";}
public void insert() {System.out.println("sql insert");}
public void update() {System.out.println("sql update");}
}
class AccessDao extends AbstractDao {
public AccessDao() {}
public String getID() {return "access";}
public void insert() {System.out.println("access insert");}
public void update() {System.out.println("access update");}
}
And the content of the Test.properties is just one line:
dao=net.SqlDao,net.SqlDao
So any ont can tell me if this suitation is necessary?
-------------------The following is added to explain the real suitation--------------
I use the example of Dao is beacuse it is common,anyone know it.
In fact,what I am working now is not related to the DAO,I am working to build a Web
service,the web serivce contains some algorithms to chang a file to other format,
For example:net.CreatePDF,net.CreateWord and etc,it expose two interfaces to client:getAlgorithms and doProcess.
The getAlogrithoms will return all the algorithms's ids,each id is realted to the
corresponding algorithm.
User who call the doProcess method will also provide the algorithm id he wanted.
All the algorithm extends the AbstractAlgorithm which define a run() method.
I use a AlogrithmsRepository to store all the algorithms(from
the properties file which config the concrete java classes of the algorithms by the web
service admin).That's to say, the interface DoProcess exposed by the web service is
executed by the concrete alogrithm.
I can give a simple example:
1)user send getAlgorithms request:
http://host:port/ws?request=getAlgorithms
Then user will get a list of algorithms embeded in a xml.
<AlgorithmsList>
<algorithm>pdf</algorithm>
<algorithm>word<algorithm>
</AlgorithmsList>
2)user send a DoProcess to server by:
http://xxx/ws?request=doProcess&alogrithm=pdf&file=http://xx/Test.word
when the server recieve this type of requst,it will get the concrete algorithm instance according to the "algorithm" parameter(it is pdf in this request) from the AlgorithmRepostory. And call the method:
AbstractAlgorithm algo=AlgorithmRepostory.getAlgo("pdf");
algo.start();
Then a pdf file will be sent to user.
BTW,in this example, the each algorithm is similar to the sqlDao,AccessDao.
Here is the image:
The design image
Now,does the AlgorithmRepostory need to use the Abstract Factory?
The main difference between the two approaches is that the top one uses different DAO factories to create DAO's while the bottom one stores a set of DAO's and returns references to the DAO's in the repository.
The bottom approach has a problem if multiple threads need access to the same type of DAO concurently as JDBC connections are not synchronised.
This can be fixed by having the DAO implement a newInstance() method which simply creates and returns a new DAO.
abstract class AbstractDao {
public abstract String getID();
public abstract void insert();
public abstract void update();
public abstract AbstractDao newInstance();
}
class SqlDao extends AbstractDao {
public SqlDao() {}
public String getID() {return "sql";}
public void insert() {System.out.println("sql insert");}
public void update() {System.out.println("sql update");}
public AbstractDao newInstance() { return new SqlDao();}
}
The repository can use the DAO's in the repository as factories for the DAO's returned by the Repository (which I would rename to Factory in that case) like this:
public AbstractDao newDao(String id) {
return daoMap.containsKey(id) ? daoMap.get(id).newInstance() : null;
}
Update
As for your question should your web-service implement a factory or can it use the repository like you described? Again the answer depends on the details:
For web-services it is normal to
expect multiple concurrent clients
Therefore the instances executing the
process for two clients must not
influence eachother
Which means they must not have shared state
A factory delivers a fresh instance on
every request, so no state is shared
when you use a factory pattern
If (and only if) the instances in your
repository are stateless your
web-service can also use the
repository as you describe, for this
they probably need to instantiate
other objects to actually execute the
process based on the request
parameters passed
If you ask to compare 2 designs from UML, 2nd API on UML have following disadvantage:
caller needs to explicitly specify type of DAO in call to getDAO(). Instead, caller shouldn't care about type of DAO it works with, as long as DAO complies with interface. First design allows caller simply call createDAO() and get interface to work with. This way control of which impl to use is more flexible and caller don't have this responsibility, which improves overall coherence of design.
Abstract Factory is useful if you need to separate multiple dimensions of choices in creating something.
In the common example case of windowing systems, you want to make a family of widgets for assorted windowing systems, and you create a concrete factory per windowing system which creates widgets that work in that system.
In your case of building DAOs, it is likely useful if you need to make a family of DAOs for the assorted entities in your domain, and want to make a "sql" version and an "access" version of the entire family. This is I think the point your classmate is trying to make, and if that's what you're doing it's likely to be a good idea.
If you have only one thing varying, it's overkill.

Categories

Resources