Java Design Patterns: Facade - java

I'm trying to make a simple ordering system, and because it's an assignment it is a delimitation that I shouldn't make DB and GUI, but I need to implement at least 4 design patterns. One of my decisions was to use Facade. As far as I understand the Facade class is kind of controller and this is what i have so far:
package model;
import java.util.ArrayList;
public class Facade {
ClientsList clients;
OrdersList orders;
ProductsList products;
ArrayList<Orders> orderlist;
public Facade() {
clients = new ClientsList();
orderlist=new ArrayList<Orders>();
orders = new OrdersList(orderlist);
products = new ProductsList();
}
public int ClientsSize() {
return clients.size();
}
public int OrdersSize() {
return orders.size();
}
public void addClients(Clients client) {
clients.add(client);
}
public void addOrders(Orders order) {
orders.add(order);
}
public void removeClients() {
clients.remove();
}
public void removeOrders() {
orders.remove();
}
public String next() {
return orders.it();
}
}
The other classes in my model package are Orders, OrdersList, Clients, Clientslist, Products and ProductsList and in the *List classes I'm holding the infromation in ArrayList. So my question is: is this code a Facade?

A facade is supposed to shield me from knowing about certain classes and the operations they implement. In your example, I may not need to know about ClientList but I do need to know about Client, Product and Order. It would be better if those classes were hidden away from me so I just need to talk to the facade.

Write an additional interface so developers dont have to work with the implementation of your facade:
public interface OrderService {
//methods your co-developers should be able to use
}
public class Facade implements OrderService {
//methods your co-developers dont want to know about
}
In your code use the interface and not the impl.

The goal of a facade is to shield the implementation of functionality in a certain component. A facade normally provides an interface to 'the outside world'. I don't know the rest of your code, but the above example could be a facade.
Say you are building a component which fetches message from social media. You could build a facade with a method 'GetMessage(string keyword)' which (obviously) returns a list of messages, regardless of the social media source. The client of this component doesn't care how the component gets data from social media, he just wants messages. Methods like 'SearchFacebook' or 'SearchTwitter' can be hidden, as the client has no interest in calling these methods. However, 'GetMessages' can use them to search Facebook and Twitter, build a list of the results of those two and return it to the client.
For another good example, check the wiki page: http://en.wikipedia.org/wiki/Facade_pattern

Intent of facade:
Provide a unified interface to a set of interfaces in a subsystem. Facade defines a higher-level interface that makes the subsystem easier to use.
Wrap a complicated subsystem with a simpler interface.
The functionality you are providing are matching with above points, so from my view It is a Facade.
In your example you are exposing sub-system(OrdersList, ProductsList) functionality though Facade.

To get more knowledge about facade design pattern, read "Head First Design Patterns"

Related

where to put the behaviour of DTOs ? Object vs Data structure clean code

Similar question was posted here Clean code - how to design this class?
I still don't find an answer though, I'm confused!
I read the book "clean code" too.He is saying in some part you shouldn't mix data structure/Object, whether data structure with no behaviour or an object with behaviour.
In my application we have Data tranfer objects which carry data from external services .These DTO have just data accessors and mutators. So I was considering them as Data structure type.
However Robert Martin is saying in his book that client.isMarried() is better than isMarried(client) I found this logical as isMarried function use attributes only from client class.. it is cleaner.
In many areas in my application we need some behaviour on a certain DTOs I'm confused where to put this behaviour.
We have made Utils classes that has business logic like
ClientUtils {
boolean isMarried(Client client) { ...}
String getCompleteName(Client client) { ...}
}
Should this go to the service layer ? even if these methods does not manipulate any thing else other than the input object It does not interact with another layer (DAL, services .. )
Since you can't change the Client class due to the external library constraint, I wouldn't extend it. I suggest making a ClientInfo wrapper class that "has a" Client member instead.
class ClientInfo {
private Client myClient;
public ClientInfo(Client c) {
myClient = c;
}
public boolean isMarried() { ...}
public String getCompleteName() { ...}
}
If you ask me, then Utils class just means you have a random static method lingering somewhere which contains actual business logic. Why not keep DTOs as DTOs, and create a ClientManager class that has isMarried method?
The ClientInfo approach that wraps the external object is another option, possibly driven by Domain Driven Security.

Designing IO adapters for web interfaces

I have a Java application which consist of a set of services. These services require I/O which is handled through an IOAdapter interface as below:
interface IOAdapter {
void info(Object arg);
void error(Throwable cause);
String read(String prompt);
boolean confirm(String prompt);
}
In the service methods, the input is obtained using some implementation of the adapter which is composed into the service instance. This adapter then handles all I/O (user interactions), and hence allows separation of that concern from the actual business logic.
For example, a typical method method would do something like:
class MyService {
IOAdapter adapter;
MyService () {
adapter = new MyAdapter(); // some implementation
}
void doSomething() {
try {
...
String val = adapter.read("Enter a value: ");
if(adapter.confirm("Are you sure?")) {
adapter.info("Value entered is: " + val);
...
} else {
doSomething();
}
} catch (Exception e) {
adapter.error(e);
...
}
}
}
Now I was able to implement an adapter which does I/O through the Java console. But, can anybody suggest a possible approach if I were to provide an implementation for a Web based adapter where the I/O happens through the browser?
Is there an alternative approach which would help solve this problem in a more straight-forward manner?
If I understand it right, you want to wrap the functionality of an HTTP server in your own service, implementing the IOAdapter interface. I think that this is not "beautiful" in the way the interface IOAdapter is written and used in the MyService class. This is because even if you write a MyHTTPAdapter the adapter.read method cannot be implemented using HTTP.
In HTTP we have two entities communicating. The client sends and the server responds. This cannot be modelled using this interface you propose, since you model only one entity and have only one method for exchanging data, method read. You have to alter the interface design, focusing on a client-server design, then you could wrap an HTTP communication.
EDIT:
Integrating the two paradigms of communication (console communication and HTTP communication) is not a trivial task. I would propose a design imposed by this interface, following the client-server architecture imposed by HTTP, supposing that a console application could implement it too:
//This should be implemented by either the HTTP or the console server Adapter
interface IOAdapter {
IOResponse serveRequest(IORequest request);
}
//This interface should be implemented by both models of IOAdapter
//For example, a subclass of string could also implement this interface in
//order to unify the two models
interface IORequest {
}
//This interface should be implemented by both models of IOAdapter
//For example, a subclass of string could also implement this interface in
//order to unify the two models
interface IOResponse {
}
Hope I helped!

is this Service layer violating SRP principle

I am developing a Web App in Spring and hibernate.
I am loading entities in Database.Authors,books,Publication etc are my entities which are getting loaded from excel.
I have mode one Entity Load Service interface and then I have its Implementations for every entity.
My Service calls DAO implementations.
Now I am struggling to find if the below mentioned code violates SRP.
Also I am always confused about how to decide responsibility of the class because any class can have many methods and each method can be performing something different.So should they be separated in different class?.take in my case I have 4 methods each performing different task.So I end up with 4 different class for each method.If I follow this approach(which I know is wrong) then I will always end up in classes having single method.
Also,sometimes I feel that I going away from domain driven design because I am refracting the code on the basis of functionality.
Any suggestions on how to decide what the responsibility is from the perspective a class?
SRP stands for single responsibility principle.And I am really confused in identifying this responsibility.
public interface EntitiesLoadService {
public void loadEntities(Object o);
public void deleteEntities(Object o);
public List getEntities();
public Object getEntity(Object o);
}
Service Implementation
#Service("authorLoadService")
#Transactional
public class AuthorEntityLoadService implements EntitiesLoadService{
private AuthorDAO authorDao;
#Autowired
#Qualifier("authorDAO")
public void setAuthorDao(AuthorDAO authorDao) {
this.authorDao = authorDao;
}
#Override
public void deleteEntities(Object o) {
// TODO Auto-generated method stub
}
#Override
public void loadEntities(Object o) {
Set<author_pojo> author=(Set<author_pojo>)o;
Iterator<author_pojo> itr=author.iterator();
while (itr.hasNext()) {
author_pojo authorPojo = (author_pojo) itr.next();
authorDao.save(authorPojo);
}
}
#Override
#Transactional(readOnly=true)
public List getEntities() {
// TODO Auto-generated method stub
return null;
}
#Override
#Transactional(readOnly=true)
public Object getEntity(Object o) {
String author=(String)o;
author_pojo fetAuthor=authorDao.findOneByName(author);
return fetAuthor;
}
}
You have AuthorDAO which is the class that should be doing all interactions with the persistence layer, ex. a database.
It isn't obvious in your example because your AuthorEntityLoadService has similar methods which just delegate to the DAO layer.
As your project and requirements grow, you will see that more methods are required for this class. These methods will be responsible for doing more than just CRUD operations on the DAO layer. They might need to interact with other services, internal or external. They might need to do multiple DAO calls.
The Single Responsibility in this case is to provide services for interacting with AuthorEntity instances.
It is on of many correct ways of implementing what you are proposing.
More specifically, my opinion on
Also I am always confused about how to decide responsibility of the
class because any class can have many methods and each method can be
performing something different.So should they be separated in
different class?
Just because you have many methods doing different things, doesn't mean the responsibility isn't shared. AuthorEntityLoadService which I would just call AuthorEntityService manages AuthorEntity instances at the service layer. Image if you had one Class with one method for each of create, update, retrieve, delete an AuthorEntity. That wouldn't make much sense.
And on
Any suggestions on how to decide what the responsibility is from the
perspective a class?
As further reading, try http://java.dzone.com/articles/defining-class-responsibility
Typically, in this type of n-tier architecture, your service layer is meant to provide an API of transactional (or otherwise resource-dependent) operations. The implementation of each service can use whatever resource-specific dependencies (like DAOs for a particular datasource) it needs, but it allows the service consumer to remain agnostic of these specific dependencies or resources.
So even if your service is just delegating to its resource-specific dependencies, it doesn't violate SRP because its responsibility is to define a resource-agnostic API (so that the consumer doesn't need to know all the resource-specific stuff) that specifies atomic operations (transactional if necessary).

How do I Design and Interface (OOP kind) in Java so that I can either use direct database access or use web services?

At the moment I have to query database that I do not own which has a web service, so what they provide is what I get. Since this is in house (sort of), I might be able to get direct access in the future so that I can get better data in my query.
I don't want to have to write everything again and again. If I did this in Java would I write an Interface (programming kind, think Implements Interface, OOP)? How would I do this? Or do I just write a whole new class and "plug it in."
This is just a regular client/server architecture. Http request, server calls the servlet or jsp, returns data.
I'm not sure if my idea is correct design or not.
Definitely sounds like you should use an interface with different implementations here. Something like:
public interface DataAccess {
Data getData();
}
Then you can code against this API and just plugin/inject a different implementation as needed. So you could have this:
public class DirectDataAccess implements DataAccess {
public Data getData() {
//use JDBC, ORM, or similar
}
}
Or this:
public class WebServiceDataAccess implements DataAccess {
public Data getData() {
//call web service
}
}
But as long as your client code only references the DataAccess interface, then you have successfully decoupled your client from your service.

state design pattern from Java to Ruby

I have a working solution in java using a classic state design pattern and facing some difficulties translating it to ruby. I am new in ruby, but the diffuclty I believe lies in the differences on how patterns can be implemented in dynamic languages.
My interface is describing the actions the model can execute in every state:
public interface State {
public void doTask1(Model a_model);
public void doTask2(Model a_model);
public boolean doTask3(Model a_model, Helper a_helper);
}
Next, I implement the state interface and create concrete states of my logic:
public class LogicState1 implements State {
public void doTask1(Model a_model) {
a_model.implementTask1();
}
public void doTask2(Model a_model) {
a_model.implementTask2();
}
public boolean doTask3(Model a_model, Helper a_helper) {
a_model.useHelper();
return a_model.setState(a_model.getALogicstate(a_key));
}
As you can see, each concrete state can reach into the model and change its State. To avoid encapsulation issues, I instantiate my concrete states within the Model class, which has also a reference to the current State:
public class Model {
private State currentState;
public void setState(State state){
this.currentState = state;
}
public State getState(){
return currentState;
}
private final Map<String, State> everyState = new HashMap<String, State>();
public Model(String initialStateKey){
everyState.put("key1", new LogicState1());
everyState.put("key2", new LogicState2());
//...etc, instantiate and store all business logic states
this.currentState = everyState.get(initialStateKey);
}
public State getALogicState(String key){
return everyState.get(key);
}
public void useHelper(){...}
A client would use the Model like this:
public void run(Model a_model) {
a_model.getState().doTask1(a_model);
}
I think all of the above Java is straightforward, but now I am attempting to port this design into Ruby. I am aware of the differences in type-checking, and how modules and mixins are supposed to work in Ruby in contrast to Java's interfaces.
I have also found out about the State design pattern in Ruby in the pickaxe book.
Now I am a bit confused about which is the best way to try such conversion. I am still thinking inside the Java box, and wondering if I should have my concrete implementation of each state in a different .rb file and then require it in the client class?
Is there a way to implement the above without using the delegate.rb library?
Any suggestions on how to start with my conversion will be enthusiastically appreciated.
To translate this to ruby you can just leave out the interface and keep everything else as is. I.e. each state is a class that defines the methods do_task_N and doesn't otherwise have a connection to the other state classes (meaning you don't have to "emulate" the common interface by mixing-in a module or anything, you simply don't need it at all).
I am still thinking inside the Java
box, and wondering if I should have my
concrete implementation of each state
in a different .rb file and then
require it in the client class?
That sounds fine, yes.
I you trying to port a specific program from Java to Ruby or are you trying to learn to write Ruby?
If #1, why?
If #2, I would recommend that you work with existing Ruby code in order to learn the Ruby style. I highly recommend Ruby on Rails for this, since it is a very well written framework.
I learned a lot of lessons from Rails, which I can use even when I write other kinds of programs and in other languages.

Categories

Resources