I am trying to apply the State Design Pattern to an instant messenger program that I am building. The program is built on top of an existing instant messenger API. I am essentially creating a wrapper class to simplify the process of sending a message. (The wrapper class is going to be used by several automated scripts to fire off messages when some event occurs.)
Here is what I have so far:
A Messenger class that will serve as the client interface and hold a reference to the current state.
An AbstractMessengerState class from which all of the concrete states will inherit.
Several concrete State classes representing the various states (e.g. SessionStarted, LoggedIn, LoggedOut, etc.)
The problem I am having is where to store the state data. That is, which class(es) should store the fields that I need to carry out the business logic of the messenger program. For example, I have a Map data structure that maps userIDs (strings) to the objects used by the underlying API. I have a Session object that is used to access various messenging components and to log in and out of the messenger server. These objects need to be shared between all the subclasses.
If I store this data in the base class than I will be duplicating data every time I instantiate a new State. Is there a way to ensure that the data in the base class is accessible by the subclasses without duplicating the fields?
UPDATED
Ok, after reading a related post I am going to try to store everything in the Context (Messenger) class and see how that goes.
Related
I have been provided with a Java Application on which to apply the Three-Tier architectural style; One of the use cases to do is the login.
I've studied all the theory and rules that apply to this architectural style, but I need to understand the logic of the objects co-operation between the various levels and how patterns work together on each level to realize this (and the others) use case.
First, I've created the three basical packages: Presentation, Application and Data. In addition, I included one more package about the Boundary classes, The various GUIs from which requests will be sent.
In the Presentation layer, I just put a Front Controller, that encapsulates the presentation logic required by clients using the application.
In the Data layer, I put a DatabaseConnection class (Class that communicates with the database and that is responsible for loading the driver, connecting to the database, querying etc.) and DAOs classes (Data Access Object, that interfaces with the database).
The real problem is that I don't know what to put in the Application level, which represents the main part of the application, defining the domain model of the application, that is: their entities, their relationships, and application logic. It should not contain any reference to how the data will be presented to the user or how they will be saved.
So, I currently have this hierarchy:
Main ---> Boundary > Presentation > Application > Data > Database
In accordance with this architecture, how can I make a simple login?
Bearing in mind that each level can communicate ONLY with the underlying level;
For example, a class in Boundary layer cannot comunicate directly with a class in Data layer, Boundary's classes can comunicate with Presentation's classes only.
If necessary, you can post a pseudocode, which makes the idea of the steps to do.
Your Boundary calls only basic methods on the Presentationlayer.
Let's say the User clicks a Button to create a User the flow would be the following: Boundary calls method createUser(String name, int age) on the FrontController (Presentationlayer). The Controller can check some basic (UI-Related) things and would then call a similar method on the Applicationlayer.
The Applicationlayer can now process some further checks (for example: is the Current Active User allowed to create a User?). The Applicationlayer takes the given informationen (name and age), creates a DAO based on that and invokes the method to create the User on the Datalayer (DAO).
The Datalayer simply inserts the given information.
I have been reading about java proxy pattern and invocation handler and everywhere it is seen that the concrete class construction is available to the client.
For example,
//TwitterService service = (TwitterService) SecurityProxy.newInstance(new TwitterStub());
TwitterService service = new TwitterStub();
System.out.println(service.getTimelinePosts("abc"));
User can create an instance of TwitterStub directly and access the methods. I was wondering if there was a way of not exposing the or avoiding the construction of the concrete class via the client ?
Is there a better way ?
As the GoF puts it, the intent of the proxy pattern is "to provide a surrogate or placeholder for another object to control access to it".
So, in your specific case what happens is that you're creating a particular proxy instance directly. And that's fine as long as you (as a client) know that you want a particular type of proxy object.
If what you want is a level of indirection, you can use an Abstract Factory Pattern that return different types of proxy objects. But so far, the reason of proxy objects is to act on behalf of other objects.
As a side note, proxies are useful when you have objects that are expensive to create, but you don't want to necessarily cripple main application function due to such expense. For example, suppose you have a document with 1000 images. You can use proxies for them, and only load them when stricly needed (i.e. when they are in visible view), and you can still load the full document really fast without the overhead of reading 1000 images at once.
I have a small component required for an application. The component that loads a csv file and then updates customer records based on the data it finds. There will be a single csv file for every customer update.
Checks a file location for csv files
For each csv file it finds, load the csv file, parse it and update the customer data with any updated data
Thats it.
However im torn between a couple of ways to do this.
Have a single Updater() class which does everything.
Have an Update() class which is a representation of the loaded csv data, this knows how to parse the csv etc. and then also have an Updater() class that is responsible for updating the customer records. The Update() class would have an Updater()
Which of these is the correct solution or are there any other better solutions to this?
If you are thinking of a real general design, consider the following:
Class UpdateSet: A list of updates. A CSV file if you want.
Interface UpdateInstance: The different types of updates, from a request point of view. A CSV line if you want.
Class InsertInstance: Implements UpdateInstance. An insert request.
Class DeleteInstance: Implements UpdateInstance. A delete request.
Class ChangeInstance: Implements UpdateInstance. An update request.
Interface UpdateSetBuilder: Produces an UpdateSet from somewhere.
Class CSVUpdateSetBuilder: Implements UpdateSetBuilder by reading a CSV file. Probably a singleton object.
Interface UpdateParser: Takes a CSV line and produces an UpdateInstance (or refuses it).
Class InsertParser: Implements UpdateParser. Probably a singleton object. Detects and parses an insert request.
Class DeleteParser: Implements UpdateParser. Probably a singleton object. Detects and parses a delete request.
Class ChangeParser: Implements UpdateParser. Probably a singleton object. Detects and parses an update request.
The different UpdateParsers are registered with the CSVUpdateSetBuilder and selected through a delegation mechanism (i.e. each of them is given in turn the opportunity of recognizing a record, if it returns null, the next UpdateParser will be given its chance).
Class Updater: Takes a collection of CustomerRecords and applies an UpdateSet to it.
Interface UpdateTypeDoer: The different types of operations, from an execution point of view.
Class InsertDoer: Implements UpdateTypeDoer. Detects InsertInstance objects and applies them to the data.
Class DeleteDoer: Implements UpdateTypeDoer. Detects DeleteInstance objects and applies a delete request to the data.
Class ChangeDoer: Implements UpdateTypeDoer. Detects ChangeInstance objects and applies an update request to the data.
The different UpdateTypeDoers are registered with the Updater and selected through a delegation mechanism (i.e. each of them is given in turn the opportunity of recognizing a record, if it returns null, the next UpdateTypeDoer will be given the opportunity).
Advantages: Very flexible, and easy to evolve and modify (add new data sources, update types, etc).
Disadvantages: A big investment in terms of design and implementation time that maybe never pays back. Are you ever going to add types of update? Different data sources? File formats?
I've always thought that in design and programming there are 2 things you can do endlessly: abstraction and indirection. Knowing how much is too little and how much is too much is the real art.
Split the functionality. It's difficult to say without knowing more about the code, but I'd say at least have the loading/parsing of the CSV separate from applying it to your internal record. I'd probably keep the code that searches the directory for CSVs separate from both of them.
I would keep it as simple as possible (1 class) for now unless you need to add more functionality. Will other classes need to get updates? If not, don't bother designing, creating (and testing) a more complication system.
If however you need multiple classes, perhaps the Observer Pattern is what you are looking for. That way other objects register that they want to get update events and your class that knows how to parse these records fires Update events. The Listening class can receive those Update events and does the actual update.
If the logic
that loads a csv file and the logic that then updates customer records based on the data it finds are both pretty simple/short then keep them in a single Updater class that first loads the data and then updates it.
If the CSV data itself is complex it might be better to make an additional class that stores the data of each object (entry in the csv file) with the appropriate mutators(setters/getters). It can still be used in a single class that reads the file, creates an object for each entry and then updates the customer records.
The only reason I could think of to split the Updater in 2 separate classes is having very complex logic of reading the file and updating the customer records. But I can't see how they could be so hard/long to implement.
Ok guys,
Here's a question more of principle than of fact.
I have a data-structure that is used on both a client and a server.
However, on the server end, I want functionality to create the client from some sort of datastore (at the moment SQL, it used to be serialized data, but it doesn't matter).
Originally I had a giant class called something like 'Datastore' which had static methods for retrieving any stored object.
While not terrible, that's not exactly OO, and it's not exactly scalable.
So I considered moving these static methods to the datastructures themselves. However, that would mean that the shared client libraries then knew how to retrieve objects from my datastore - which is kind of silly.
So I'm now creating new classes for each object in a new datastore package, each of which holds the static methods for retrieving one object from the datastore.
My question is, how do I signify the relationship between these data manager classes and the objects that they retrieve?
Functionally, it doesn't matter. The static methods work fine. But I want to indicate to future me and other future developers that the data retriever class and the object class are tightly linked.
My first thought was to make the data retriever extend the data structure. However, that would then require declaring default constructors and implying that the class could be instantiated - which it can, but why would you?
My second thought was to then make the data retriever extend the data structure, but be abstract. That would flag the tight relationship to other developers, and also make it clear that only new methods were being added, no new fields.
However, extending a concrete class with an abstract class seems really strange, and Java still make me create default constructors.
My question is, how do I signify the relationship between these data manager classes and the objects that they retrieve?
This is a standard industry problem: how to get data from a database into an application. The common solution is to use the DAO pattern, which is to have a Data Access Object (DAO) responsible for retrieving an object from the database.
If you are retrieving an employee's personal information, salary, etc., you could have an EmployeeDAO class which would retrieve it from the appropriate table. If you are retrieving a company's profits, locations, number of employees, you could have a CompanyDAO class to retrieve this object from the database.
On top of this could be a service layer, for performing business logic; also, a DAO manager, for instantiating the DAOs and returning references to whatever classes need them.
You can still merge concepts of Repository Design Pattern and DAO Pattern, taking the application in a more concise abstraction level. The Repository acts as domain-level abstraction. Example:
public class EmployeeBO implements EmployeeRepository { // implementation of a Business Object Domain-model
#Inject
private EmployeeDAO employeeDAO; // really implementation of data access
#Override
public boolean createEmployee(String name){ // domain-oriented method
// ... some validation
employeeDAO.save(new Employee(name)); // really data access/persistence implementation
}
}
I am implementing a game/application where the player's account/state is synced to the server. I am contemplating a general framework communicating modifications of nested objects of an entity (the entity being the users's account). Let us assume for discussions of computation/reflection that both the client and server are written in Java (in reality client is in Actionscript which can modify properties dynamically)
Take for instance Firebase. Modifications to any object of the root object (a Firebase object) are propagated with a request that probably looks something like:
Service: PersistenceService
Action: modifiedObjects
Body:
Objects [{"/full/Path/To/Object/1","newValue"},{"/full/Path/to/Object/2","newValue"}]
My request for your input is the following:
1) Please correct and/or augment the following thoughts on implementing this general framework for propagating modifications to a tree of objects.
On the sending side, it would appear that every object either:
1) Needs to store it's full path from the root entity
2) Changes to properties of all nested objects need to be done reflectively
OR
A sync needs to forced, comparing the entity's saved object tree from the last request to the current object tree for modifications.
On the server side, one can analyze the paths of the objects to cache objects that are accessed multiple times in one request so as not to access the tree by reference/search collections multiple times.
The answer I have come up with is actually very obvious the obviously the best way to do it. The answer is to mirror a database of tables. Assign each object an id, and store every object in an ArrayList (or assign each object a unique ID based on type and store the object in its type's ArrayList which is itself stored in a HashMap).
I call my interfaces ServiceObject and ServiceContainer.
Now the only thing I have to see that works is how json and protostuff serialize dual references to objects. Are they serialized as seperate objects? If so, than I any nested ServiceObject's need to deserialized as references to the objects in the ArrayList.
Generally observer pattern is answer to kind of requirement you have (from wiki)
The observer pattern (aka. Dependents, publish/subscribe) is a software design pattern in which an object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods. It is mainly used to implement distributed event handling systems.
You need implementation on the client server hence example given on the wiki is not applicable you might want to check this :
http://deepintojee.wordpress.com/2011/03/18/observer-pattern-applied-at-remote-level/