Design Pattern - which one?

Hello,
We have a system where the frontend(which is not the GUI)but which simulates a subset of GUI and passes on the commands(requests) and log the response data from the backend.

We feel that there is a scope for improvement in next version of our product.As a sidenote this is in Java.

Now the current design is partitioned into 2 classes in which

Class A ==> subset of commands for Global administrator all implemented as separate functions(methods in Java)

Class B ==> subset of commands for Local administrator all implemented as separate functions(methods in Java)

Each time we get a request we do the checks and then spawn either a Class A /Class B object with the relevant parameters.

Now Class A/B are becoming huge and unmanageable.We are also running into Memory problems(Java is horrible in memory management,yet to improve ,how I wish there was a 'delete object' ,sigh...)

The desired solution will have extensibility in that we can add new commands to either of them easily.

Mind you the data is parsed from the simulated GUI/ and formatted for backend in the above 2 classes for all the implemented commands.

A complete redesign is on the cards and some help in brainstorming with design patterns is sought with justifiction for our client.

Also I was thinking since we are spawning those 2 classes can't we have static functions(methods in Java) for all commands ,so that memory footprint is conserved?And we doont have to spawn objects?

please advise

p.s deliberately keeping low points ,since posted in C++ & Java sections
DesignPatternsAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

JodCommented:
What is the lifespan of the Object A and Object B classes and how many concurrent users do you have? In other words, do you need more than one concurrent Object A or Object B?

It is quite possible you can use static methods, but I'd need to know a bit more about how the application is used. Static methods would also help with your memory management problems - reuse of objects in Java is highly recommended.

Could you clarify what you mean by a simulated GUI? Do you mean that you have an interface that accepts remote commands and then passes them on? How do the users acccess the application?
0
DesignPatternsAuthor Commented:
Jod,

>>>>>What is the lifespan of the Object A and Object B classes and how many concurrent users do you have?

Many users,so i think that these objects be in memory throughout.

>>>>>In other words, do you need more than one concurrent Object A or Object B?

sorry for not clarifying earlier but
our 'command' is just a static final int (much like const int)with which the frontend sends like

guiRequestHandler.sendCommand(int command,String data);

sendCommand() is synchronized so when we send command ,a new Class A object or Class B object is invoked and then callback the backend.

so I think that no need for taht and those objects r not threads.

>>>>>
Could you clarify what you mean by a simulated GUI?...

it's a command line utility.
0
JodCommented:
Does every sendCommand() create a new object?
0
Cloud Class® Course: Python 3 Fundamentals

This course will teach participants about installing and configuring Python, syntax, importing, statements, types, strings, booleans, files, lists, tuples, comprehensions, functions, and classes.

JodCommented:
Or does it just invoke an existing one if possible and how do you currently store and track your Object A and Object B's?
0
DesignPatternsAuthor Commented:
Jod,
this is the reply I posted at C++ section

KangaRoo,

I am pushing for a RegEx package for parsing but i dont know if they would approve as it's a third party package ,but thanks anyway.FYI it is a readymade implementation of the Interpreter customised for my need.

yonat,
>>>>>
What does sendCommand do?
Is it a part of the program you are responsible for, or are you just calling it?

basically the cmd line is sitting at the server side ,client sends a command with optional data.If client wants a list for example then data is balank but response data is the list of whatver they want.

If client wants to do a save/apply then they send relevant data & response is OK or if some prob ,some indication.

>>>>>What does the part of the system that you are developing responsible for?

so I mostly have to redesign the name-value pairs parsing,validation per name-value pair,1 record validation and lastly inter record validation

>>>>>Getting command codes and deciding where to send them, or deciding what action to perform when a certain command is invoked? Or maybe something else?

so the comand codes are fixed (static int ,KangaRoo I dont understand C++ syntax that much ,sorry.) in some file client just calls them and sends data so I have to just call the guiRequest object's sendCommand()with some diff mapped opcodes and the changed data after parsing,validation& required formatting

gysbert1
yonat & u r absolutely right in that I will have to use multiple patterns.

yonat & KangaRoo mentioned for me to use the Command but I was not thinking right ,yonat went and said abt the dictionary using the Proactor.

what I was thinking of was this,sorry if it's in Java but I cant think C++


//to implement Command Pattern
//this si much like a class having a pure virtual function

public interface Validator
{
      public boolean validate(String oneRecord);
}

//First Concrete implementation of Validator
public class Type000Validator implements Validator
{
      //bunch of private methods & data PLUS the common validate()

      public boolean validate(String oneRecord)
      {
         //validate the recoerd & return if success/failure
      }
}

public class Field
{
      private Field [] toSearch=null;
      private String fieldName=null;
      private boolean isCompulsory=false;
      private boolean isBlankAllowed=false;

      public Field(String f,boolean isC,boolean isB)
      {
       this.fieldName=f;
         this.isCompulsory=isC;
         this.isBlankAllowed=isB;
      }

      public String getFieldName()
      {
         return fieldName;
      }
      public void setFieldName(String name)
      {
         if(name!=null && name.trim().length()>0)
            fieldName=name;
      }

      ///similar methods for the 2 booleans.

      public static void setFieldArray(Field[]f)
      {
          this.toSearch=f;
      }
      public static int isNamePresent(String name)
      {
         if(toSearch==null)
            throw new Exception("Array is not initialized");

         int toReturn=-1;
         for(int i=toSearch.length;--i>=0;)
         {
           if(toSearch[i].getFieldName().equals(name))
           {
              toReturn=i;
              break;
           }
       }

       ///not found
       return toReturn;
    }
}

public interface GenericParser
{
   public String genericParsingMethod(Field[] names,String data,Validator v);
}

public Class A implements GenericParser
{
    private static final Field [] type000Array = new Field[3];

    static
    {
            //this type000 consists of 3 name-value pairs only
            type000Array = new Field[3];
            type000Array[0]=new Field("IDName",true,false);
            type000Array[1]=new Field("Address",true,false);
            type000Array[2]=new Field("StreetNumber",false,true);
      }

    public String saveType000Command(int command,String data)
      {
            String inFormat=genericParsingMethod(type000Array ,data,new Type000Validator());
        guiReqHandelr(command,inFormat);
      }

    //only concrte implementation of GenericParser interface
    public String genericParsingMethod    (Field[]names,String data,Validator v)
    {
    /*
    (1)pick up 1 record using regex package
    (2)validate the record using
     v.validate(oneRecord)
    */
    }
}


the only thing I think is lacking is that I cant seem to make this dynamic i.e if I dont have the class Field & an Array I will have 1 class for each command so If rigth now we have 80 commands 80 class files! Can anybody suggest any changes?

I think that I have implemented Command pattern in the Validator ,is this OK?

the interpreter is the Regex package

I believe that the Visitor can be applied as GenericTypeXXXCommand
but I cant figure out how right now
0
DesignPatternsAuthor Commented:
to answer ur questions
(1)Does every sendCommand() create a new object?

No,existing object for that session

(2)how do you currently store and track your Object A and Object B's?

We allocate it every time we get a new command request from the SAme Client,i.e client sends list() ,we alloc 'A' then sometime later save() again we alloc 'A' ,etc .. so depending on command alloc either 'A' or 'B'.
0
JodCommented:
Makes more sense now - I'm a bit snowed under today, but I'll have a think about this and get back to you a bit later...
0
DesignPatternsAuthor Commented:
I have implemented the command pattern+interpreter from Regex package and sent it to my senior for approval,will tell u the result sometime later

Thanks
0
JodCommented:
Sorry I have had so little time to check back on this this week.

If your boss is like most bosses though, he won't have a clue what you are going on about and sign off whatever you suggest.

But I am just a cynic...

(If I feel I have something useful to add I will get back to you but it needs a bit of thought and I am very short on time at the moment)
0
DesignPatternsAuthor Commented:
TAN TAN TAN TAN TAN TAN TAN TAN TAN TAN TAN TAN TAN TAN TAN TAN TAN TAN TAN TAN TAN TAN TAN TAN TAN TAN TAN TAN TAN TAN TAN TAN TAN TAN TAN TAN TAN TAN TAN TAN TAN TAN TAN TAN TAN TAN TAN TAN TAN TAN TAN TAN TAN TAN TAN TAN TAN TAN TAN TAN

Jod,
many thanks to the guys at the C++ section, my boss has approved the initial design,we are going to sit down and hammer the issues in detail.
Will need your help much later ,as I will ve snowed under till Sunday atleast.

Thanks
0
Ravindra76Commented:
Fine discussion
0
DesignPatternsAuthor Commented:
i am afraid to reprt that they have rejected the Reg ex package and i have to do the whole parsing myself.

somebody shoudl invent a Boss Pattern ,i.e when Boss is doing this we do taht etc...

probably we can fill some pretty cool patterns
:)
0
DesignPatternsAuthor Commented:
Jod,
can you lock this question so I can give you points?
0
JodCommented:
Thank you DesignPatterns but I really don't feel I have earned the points here - feel free to delete this question and save the points up for a future question.

It is an interesting problem but I didn't really have time to think about it - in general most of the questions here require less thought than this so it is a shame that I don't have time for the challenge but there you go...

0
JodCommented:
Some links that will help are:

www.ootips.org

though the code is in C++ the info is very useful.


Also have a look into JavaCC as a parser generator - your boss cannot reject this as what it does is generate a program that does parsing for you based on a specified grammar that you provide.

Comes with many pre-prepared grammars and may just save you a lot of time:

http://www.metamata.com/JavaCC/FAQ/
0
DesignPatternsAuthor Commented:
Can you explain the Visitor pattern ,I have been trying to understand it and couldnt,if u agree then I will post a new question for you to answer.
0
JodCommented:
I'll just put the answer here if you like...


The visitor pattern is useful when you want to centralise code that has to do the same thing but to different classes which can have very little in common.

Each class that wants to have an action performed on it, must implement a method called accept (as in, "accept a visit from a visitor").

The way this works, is that in your Visitor class you may need to iterate through a number of objects and perform certaion functions on each instance.

It may be, for example that it is not practical to copy all the necessary support methods and data to support these functions in every class that needs to be processed so you look at it from a different angle.

Your visitor class calls the accept method of every object it is to process. accept looks like this:

public void accept(Visitor v) {
      v.visit(this); //call visitor method
}

As you can see from the code, all accept does is invoke the visit method of the visitor and pass itself in as a reference.

Now that the Visitor has a reference to the object it can do as it pleases with it and process it in it's visit method and you can have any number of different visitors that do different things with the object.



Here is an example from Design Patterns in Java:

NOTE THOUGH THAT THIS CODE APPEARS TO HAVE BEEN WRITTEN BY C++ PROGRAMMERS AS THEY HAVE USED AN ABSTRACT BASE CLASS TO CREATE THE VISITOR TYPE. IN JAVA YOU COULD AND SHOULD USE AN INTERFACE. JUST A NOTE ON AN OVERSIGHT ON THE CODE BELOW WHICH IS OTHERWISE A GOOD BASIC EXAMPLE.

Just thought that was worth mentioning anyway...now we begin

************

We have a simple Employee object which maintains a record of the employee’s name, salary, vacation taken and number of sick days taken. A simple version of this class is:

  public class Employee {
        int sickDays, vacDays;
        float Salary;
        String Name;

        public Employee(String name, float salary, int vacdays, int sickdays) {
              vacDays = vacdays; sickDays = sickdays;
              Salary = salary; Name = name;
        }

        public String getName() { return Name; }
        public int getSickdays() { return sickDays; }
        public int getVacDays() { return vacDays; }
        public float getSalary() { return Salary; }
        public void accept(Visitor v) { v.visit(this); }
  }

Note that we have included the accept method in this class. Now let’s suppose that we want to prepare a report of the number of vacation days that all employees have taken so far this year. We could just write some code in the client to sum the results of calls to each Employee’s getVacDays function, or we could put this function into a Visitor.

Since Java is a strongly typed language, your base Visitor class needs to have a suitable abstract visit method for each kind of class in your program.

In this first simple example, we only have Employees, so our basic abstract Visitor class is just

  public abstract class Visitor {
    public abstract void visit(Employee emp);
  }

Notice that there is no indication what the Visitor does with each class in either the client classes or the abstract Visitor class.

We can in fact write a whole lot of visitors that do different things to the classes in our program. The Visitor we are going to write first just sums the vacation data for all our employees:

  public class VacationVisitor extends Visitor {
    protected int total_days;
    public VacationVisitor() { total_days = 0; }
   
    //-----------------------------
    public void visit(Employee emp) {
      total_days += emp.getVacDays();
    }
    //-----------------------------
   
    public int getTotalDays() {
      return total_days;
    }
  }
 
 
Visiting the Classes

Now, all we have to do to compute the total vacation taken is to go through a list of the employees and visit each of them, and then ask the Visitor for the total.

  VacationVisitor vac = new VacationVisitor();

  for (int i = 0; i < employees.length; i++) {
    employees[i].accept(vac);
  }
  System.out.println(vac.getTotalDays());
 
So, for each visit:

1. We move through a loop of all the Employees.
2. The Visitor calls each Employee’s accept method.
3. That instance of Employee calls the Visitor’s visit method.
4. The Visitor fetches the vacation days and adds them into the total.
5. The main program prints out the total when the loop is complete.

***************


Do you see the point of this? It allows lots of different types of class to have the same thing done to them.

The key to understanding this code pattern is here:

  for (int i = 0; i < employees.length; i++) {
    employees[i].accept(vac);
  }

What you are achieving by this, is allowing each of your employee classes to be processed.

BUT, rather than pass the employees class in to an object to do the calculation, you do it the other way round and pass the processing object (a Visitor) into the accept method of the each employee instance.

This allows you to pass different visitors (processing objects) into the employee to do different things without having to change the employee code.

In other words, it provides a nice easy way to add functionality and new classes without affecting the stability of your existing code.

It is also quite neat.

The real advantage would come if you had different types of employee or a class representing a whole group of employees to process the leave days for in a similar way. The implementation of visit can be changed to handle whatever you like.

The last point about this design is then that you can end up separating your code and data logically - you have object classes such as employee to store your data and Visitor classes such as VacationVisitor above to process the data in them.

Is this any clearer now?
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
DesignPatternsAuthor Commented:
Yes it is ,but I will read it in detail later on.anyway making this a PAQ now.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java

From novice to tech pro — start learning today.