Strategy Pattern Q

Hi,
I've been reading about the Strategy Pattern and I would liek to implement into one of my own small projects.
I have an application called WatchDog, this application checks some directories (provided as parameter) and puts every item in a directory in an appropriate mysql table.
I have this section in my code:
private void insertFile(File aFile, String arg) {
          if (arg.equals("/EBooks"))
               qry.InsertEbook(aFile);
          else if (arg.equals("/MP3"))
               qry.insertMP3(aFile);
                else if (arg.equals("/Videos"))
               qry.insertVideo(aFile);
     }this looks like a perfect candidate for Strategy Pattern to me?
But I'm struggling with the design.
The concept is an insert query, or simpler a query right?
The strategy interface is DataType (EBooks, MP3, Videos, ...)
And Ebook, MP3, Video are ConcreteStrategy classes then???
Can anybody give some clarification on this one pls?
grtz

Not necessarily the Strategy Pattern proper or the best possible solution but you could do something like this:
interface FileHandler
   public void handle(File file);
}And then in in another class:
private Map<String, FileHandler> handlers = new HashMap<String, FileHandler>();
// fill the map with a handler for each directory
private void insertFile(File aFile, String arg) {
   handlers.get(arg).handle(aFile);
}

Similar Messages

  • How to implement Strategy pattern in ABAP Objects?

    Hello,
    I have a problem where I need to implement different algorithms, depending on the type of input. Example: I have to calculate a Present Value, sometimes with payments in advance, sometimes payment in arrear.
    From documentation and to enhance my ABAP Objects skills, I would like to implement the strategy pattern. It sounds the right solution for the problem.
    Hence I need some help in implementing this pattern in OO. I have some basic OO skills, but still learning.
    Has somebody already implemented this pattern in ABAP OO and can give me some input. Or is there any documentation how to implement it?
    Thanks and regards,
    Tapio

    Keshav has already outlined required logic, so let me fulfill his answer with a snippet
    An Interface
    INTERFACE lif_payment.
      METHODS pay CHANGING c_val TYPE p.
    ENDINTERFACE.
    Payment implementations
    CLASS lcl_payment_1 DEFINITION.
      PUBLIC SECTION.
      INTERFACES lif_payment.
      ALIASES pay for lif_payment~pay.
    ENDCLASS.                 
    CLASS lcl_payment_2 DEFINITION.
      PUBLIC SECTION.
      INTERFACES lif_payment.
      ALIASES pay for lif_payment~pay.
    ENDCLASS.                   
    CLASS lcl_payment_1 IMPLEMENTATION.
      METHOD pay.
        "do something with c_val i.e.
        c_val = c_val - 10.
      ENDMETHOD.                   
    ENDCLASS.                  
    CLASS lcl_payment_2 IMPLEMENTATION.
      METHOD pay.
        "do something else with c_val i.e.
        c_val = c_val + 10.
      ENDMETHOD.  
    Main class which uses strategy pattern
    CLASS lcl_main DEFINITION.
      PUBLIC SECTION.
        "during main object creation you pass which payment you want to use for this object
        METHODS constructor IMPORTING ir_payment TYPE REF TO lif_payment.
        "later on you can change this dynamicaly
        METHODS set_payment IMPORTING ir_payment TYPE REF TO lif_payment.
        METHODS show_payment_val.
        METHODS pay.
      PRIVATE SECTION.
        DATA payment_value TYPE p.
        "reference to your interface whcih you will be working with
        "polimorphically
        DATA mr_payment TYPE REF TO lif_payment.
    ENDCLASS.                  
    CLASS lcl_main IMPLEMENTATION.
      METHOD constructor.
        IF ir_payment IS BOUND.
          me->mr_payment = ir_payment.
        ENDIF.
      ENDMETHOD.                  
      METHOD set_payment.
        IF ir_payment IS BOUND.
          me->mr_payment = ir_payment.
        ENDIF.
      ENDMETHOD.                  
      METHOD show_payment_val.
        WRITE /: 'Payment value is now ', me->payment_value.
      ENDMETHOD.                  
      "hide fact that you are using composition to access pay method
      METHOD pay.
        mr_payment->pay( CHANGING c_val = payment_value ).
      ENDMETHOD.                   ENDCLASS.                  
    Client application
    PARAMETERS pa_pay TYPE c. "1 - first payment, 2 - second
    DATA gr_main TYPE REF TO lcl_main.
    DATA gr_payment TYPE REF TO lif_payment.
    START-OF-SELECTION.
      "client application (which uses stategy pattern)
      CASE pa_pay.
        WHEN 1.
          "create first type of payment
          CREATE OBJECT gr_payment TYPE lcl_payment_1.
        WHEN 2.
          "create second type of payment
          CREATE OBJECT gr_payment TYPE lcl_payment_2.
      ENDCASE.
      "pass payment type to main object
      CREATE OBJECT gr_main
        EXPORTING
          ir_payment = gr_payment.
      gr_main->show_payment_val( ).
      "now client doesn't know which object it is working with
      gr_main->pay( ).
      gr_main->show_payment_val( ).
      "you can also use set_payment method to set payment type dynamically
      "client would see no change
      if pa_pay = 1.
        "now create different payment to set it dynamically
        CREATE OBJECT gr_payment TYPE lcl_payment_2.
        gr_main->set_payment( gr_payment ).
        gr_main->pay( ).
        gr_main->show_payment_val( ).
      endif.
    Regads
    Marcin

  • Strategy Pattern, Am i on the right Track?

    The question:
    Design a small, prototype, application, which creates, stores and amends warehouse records. This may have little more than a StockItem class.
    Using each of the patterns Strategy, Decorator, Adaptor and in turn provide three different adaptations to your prototype application which will enable a user to view the warehouse records in at least three different ways, e.g. by location, alphabetically, by value, by quantity in stock, as continuous plain text, as formatted text, in a list pane, as a printout etc
    My Code
    package warehouse;
    public class StockItem
        private int id;
        private String describtion;
        private double price;
        private int  quantity;
        private String location;
        ViewByLocationBehavior locationVar;
        public StockItem()
        public void setId(int id)
            this.id=id;
        public int getId()
            return id;
        public void setDescribtion(String describtion)
            this.describtion=describtion;
        public String getDescribtion()
            return describtion;
         public void setPrice(double price)
            this.price=price;
        public double getPrice()
            return price;
        public void setQuantity(int quantity)
            this.quantity=quantity;
        public int getQuantity()
            return quantity;
        public void setLocation(String location)
            this.location=location;
        public String getLocation()
            return location;
        public void setViewByLocationBehavior(ViewByLocationBehavior locationVar )
            this.locationVar=locationVar;
       public void displayByLocation()
        locationVar.displayByLocation();
        public String toString()
            return String.format("%d %S %f %d %S",id ,describtion,price,quantity,location);
    }The interface
    package warehouse;
    public interface ViewByLocationBehavior
        void displayByLocation();
    }Concrete classes arepackage warehouse;
    public class PlainText extends StockItem implements ViewByLocationBehavior
        public void displayByLocation()
            System.out.println("Display PlainText");
    package warehouse;
    public class FormattedText extends StockItem implements ViewByLocationBehavior
        public void displayByLocation()
            System.out.println("Display Formatted Text ");
    package warehouse;
    public class ListPane extends StockItem implements ViewByLocationBehavior
        public void displayByLocation()
            System.out.println("Display ListPane");
    package warehouse;
    public class PrintOut extends StockItem implements ViewByLocationBehavior
        public void displayByLocation()
            System.out.println("Display PrintOut ");
    package warehouse;
    public class StockTest
        public static void main(String args[])
            StockItem obj = new StockItem();
            obj.setViewByLocationBehavior(new PlainText());
            obj.displayByLocation();
            System.out.println(obj.toString());
    }But my questions is Am i on the right track applying the Strategy pattern?
    Because next i will make the other Interfaces: View by alphabetically, by value, by quantity, and their Concrete Classes are
    Display as continuous plain text, formatted text, in a list pane, and printout.
    Each interface have four concrete classes
    Need your comments Please?

    But my questions is Am i on the right track applying
    the Strategy pattern?Your assignment explicitly calls for the strategy pattern:
    "> Using each of the patterns Strategy, Decorator,
    Adaptor and in turn provide three different
    adaptations to your prototype application which will
    enable a user to view the warehouse records in at
    least three different ways, e.g. by location,
    alphabetically, by value, by quantity in stock, as
    continuous plain text, as formatted text, in a list
    pane, as a printout etc"I'm not sure I care for that interface much. I would have expected something more like this (I'm not 100% sure about the parameter that I'd pass, if any):
    public interface StockItemFilter
        List<StockItem> filter(List<StockItem> unfilteredStockItems);
    }Now you'll pass in an unfiltered List of StockItems and return the List of appropriate StockItems filtered alphabetically, by location, etc. If you want to combine the fetching of StockItems with filtering, replace the unfiltered List with some Criterion.
    Your ViewByLocationBehavior doesn't seem to accept any input or return anything. What good is it?
    %

  • Strategy pattern question.

    Can the following scenario be called strategy pattern?
    public class StrategyExecutor {
         public static void main(String[] args) {
              Strategy[] strategies = {new FirstImpl(), new SecondImpl()};
              for(int i = 0; i < strategies.length; i++){
                   System.out.print("Strategy ["+ i +"] ");
                   strategies.solve();
    public interface Strategy {
         public void solve();
    public abstract class AbstractClass implements Strategy{
         public void solve(){
              int result = getFirstParam()+getSecondParam();
              System.out.println(" Result "+result);
         protected abstract int getSecondParam();
         protected abstract int getFirstParam();
    public class FirstImpl extends AbstractClass {
         protected int getSecondParam() {          
              return 22;
         protected int getFirstParam() {          
              return 11;
    public class SecondImpl extends AbstractClass {
         protected int getSecondParam() {
              return 44;
         protected int getFirstParam() {          
              return 33;

    To be a perfect fit for Strategy pattern, if the abtract class which has the template to solve() is not there and the actual algorithm is down in the FIrstImpl, SecondImpl then its a true strategy?
    Design point of view it can be a strategy pattern..
    but If you see from the the context and the programs
    objective, It is not strategy pattern

  • Can delegate and strategy patterns coexist ?

    Say I have an interface for persistence call that PersistenceInterface.
    Now for MySQL I created MySQLPersistenceClass and for DB2 I created one more class DB2PersistenceClass.
    Now to proceed with my busines slogic I have a class BusinessLogicHandler class.
    BusinessLogicHandler has a class member say persistenceObject of type PersistenceInterface. Now certainly I'm switching the persistence based on the actual implementation so I say Im using STRATEGY pattern here
    But for create operation from business layer i.e. BusinessLogicHandler.create directly invokes persistenceObject.create in this case can I say that Im using DELEGATE pattern also
    So can I say the set of classes and interface = DELEGATE + STRATEGY ?
    Thanks a lot

    Can someone please answer this ?yes
    can I say the set of classes and interface = DELEGATE + STRATEGY ?yes
    Can delegate and strategy patterns coexist ?yes
    I'd say it would be odd to use Strategy not as a delegate.

  • Strategy Pattern and HotSpot optimization

    I wonder whether using the Strategy Pattern affects HotSpot optimizations such as inlining. Assume for a non trivial operation that has to be done often there exist two alternatives which are frequently exchanged (i.e. the flag in the example changes its value frequently). Originally code looked like this:if ( caseSensitive ) {
       caseSensitiveComparison( strA, strB );
    else {
       caseInsensitiveComparison( strA, strB );
    }Assume both methods are private then that code can be inlined quite easily by the HotSpot engine.
    If we now delegate to a StringComparator (defined as interface and implemented by two singletons) we getcomparator.compareStrings( strA, strB );Is the VM still able to inline this? Or is it likely that overall performance degrades since the virtual call is not optimized away?
    Any ideas?
    Thanks!
    robert
    For further info on the Strategy Pattern see here
    http://c2.com/cgi/wiki?StrategyPattern

    That's true, but OTOH he describes a realistic (?)
    scenario in the first paragraph that explains inlining
    could occur.That's good news.
    However, what I found more valuable is his statement,
    that a virtual call is not necessarily worse than a
    local conditional (branch prediction hassles).Just to be clear, I'm not advocating the use of if instead of Strategy in some hope that it will result in inlining. Personally, I feel that the whole idea that OO slows things down is overblown. While it may add complications and more instructions at a microscopic level, OO often simplfies and reduces actions at a macroscopic level.
    I'm more interested in knowning what are the inlining requirements and triggers. Along the lines of the understanding why it's sometimes bad practice to use + for String concatenation, I'd like to know if there are simple things that can be done to improve performance with out changing the overall design.
    If anyone has any information on this it would be much appreciated.

  • Filemonitor - Strategy pattern?

    Hi all.
    I have an application that I think needs to use the strategy pattern but I'm not sure.
    I'm fairly new to design patterns but I would like to be able to use the right one and as yet I can't see which one to use and where.
    My first instance of the application places a listener on a file in the local file system and when the modified date of that file changes it notifies the application that the file has changed.
    Fairly simple.
    I have a need now to monitor files not only on the local file system but also on a ftp server.
    I thought of adding this into the class but then I thought "what would happen if I wanted to monitor a file in a database, on a remote system, somewhere I hadn't thought of, etc".
    So a design pattern was needed... but which one.
    I thought the Strategy pattern looked best from my reading but I'm not sure. I don't want to use the wrong pattern and end up having a more complicated design than I started with.
    I hope someone can help. If I haven't put enough information here then I do apologize and will put more if requested.
    Thanks in advance.
    All the best,
    Tony

    As of my knowledge ,startegy pattern would best fit.
    You can have an abstract strategy class
    public abstarct FileMontor {
    abstract void checkFile(Object file);
    public class LocalFileMonitor extends FileMonitor
    //Override the method checkFile(Object file) and write code
    public class DBFileMonitor
    //Override the method checkFile(Object file) and write code
    //In the same fashio we can keep on creating the strategies.
    But now the problem is who decides which strategy to use at what point of time, is there a way i can register the various strategies ...
    So you should have register cum controller class, where you can register all ur strategies.. and it should have intelligenece to choose the strategy at runtime from the input it is receving at runtime.

  • Mapping a strategy pattern with Hibernate

    Hey, I asked this on some Hibernate forums:
    http://forum.hibernate.org/viewtopic.php?t=992598&sid=a35abfede898ac38c0569348986fb54a
    But no one is replying... Maybe some of you know how to do this. If you need me to transcribe the message here, just tell me and I'l happily do so.

    Hibernate is for mapping object data to a relational data model. It sounds like you want to map behavior (that's what a Strategy describes), which isn't an appropriate persistence model for Hibernate. One possible solution would be to store a description of the behavior (i.e., data) and use a custom user type to define the persistence.
    ~

  • Self-Mutation With Strategy Pattern

    I have a class whose behaviour changes with state. The current behaviour is determined by a Strategy object. Often, after a given Strategy executes, it needs to change the object's active strategy, so that on the next call a new Strategy will be called. The sample class below illustrates this concept, compiles, and works.
    public class Test {
         public static void main (String[] args) {
              Test t = new Test();
              t.doIt();
              t.doIt();
              t.doIt();
         private Strategy mStrategy = new Strategy1();
         public void doIt() {
              mStrategy.doIt();
         interface Strategy {
              public void doIt();
         private class Strategy1 implements Strategy {
              public void doIt() {
                   mStrategy = new Strategy2();
    //Is the currently executing object now susceptible to garbage collection???
                   System.out.println("Executing Strategy1");
         private class Strategy2 implements Strategy {
              public void doIt() {
                   mStrategy = new Strategy1();
                   System.out.println("Executing Strategy2");
    }But question is: Is it safe? It seems that, where the code is marked with a comment, the currently executing strategy is no longer referred to by mStrategy, and so could possibly be garbage collected?
    Or is this perfectly legal, because the collector will not collect an object which is still executing code?
    Thanks for any explanation,
    John

    Maybe I'm missing something, but it seems like a lot
    of overhead to create a new object and have the old
    object garbage collected just to change strategies.No, you're not missing anything.... I could of course store the two strategies as member variables and switch in the appropriate one.
    I just did it that way because in my app the strategy objects themselves have a state which needs to be reset when they are made active. Since they aren't switched very often, it's easier just to create new ones rather than add resetState() methods to the strategy objects...
    Anyway, I agree with your point.
    Thanks again,
    J

  • Design Patterns: Do you have a good STRATEGY?

    1. Context: Create a XML file. And since there
    are many ways: DOM, WAY1, OTHERWAYS, ETC...
    2. Question: As a Design Patterns application purpose,
    can we use the Strategy Pattern? Is it appropriate one?
    If not, what are the alternatives?
    CLIENT
    --CREATEXML (CONTEXT)
    ----CREATEXMLSTRATEGY (STRATEGY)
    ------CREATEXMLSTRATEGY_DOM (CONCRETE STRATEGY)
    ------CREATEXMLSTRATEGY_WAY1 (CONCRETE STRATEGY)
    ------CREATEXMLSTRATEGY_OTHERWAYS (CONCRETE STRATEGY)

    Hi Paul,
    I have myself recently started doing the Design Patterns and believe me after understanding the Patterns OOD have become more clear. >>1. Context: Create a XML file. And since there are many ways: DOM, >>WAY1, OTHERWAYS, ETC...
    My understanding regarding the Strategy and Tempelate method Pattern has become stronger after reading the "Thinking in Patterns in Java" , the author is mentioning there these Behavioural Patterns are used for Framework development , infact there he has used example of Framework development.
    Now regarding your question it seems to me that your entire applicaiotn can use the Creational Pattern , like Abstract Factory.You can use the DOM,WAY1,OTHERWAYS as the concrete Prodcuts and all will be extracted from the Factory XMLGeneratorFactory.
    Strategy Pattern is changing the algorthims at the run time , the temlate can work for your applicaiton but then what you are trying to achieve.Currently this much I can say ..
    Let us see for more opinions
    Regards
    Vicky

  • Pattern Strategy and generics

    Hi there !
    I'm trying to implements a strategy pattern by using generics.
    That is my attempt for the abstract part :
    public interface Strategy<C extends Compound> {
            public abstract void apply(final C c);
        public abstract class Compound {
            Strategy<? super Compound> strategy;
            public void setStrategy(Strategy<? super Compound> strategy) {
                this.strategy = strategy;
            public final void move() {
                this.strategy.apply(this);
        }But when I want to use it :
        public class AStrategy implements Strategy<ACompound> {
            public void apply(ACompound compound) {
                return;
        public class ACompound extends Compound {
            public ACompound(AStrategy strategy) {
                // setStrategy(Strategy<? super Compound>) in Compound cannot be applied to (AStrategy)
                this.setStrategy(strategy); // BOOM !
        }So I think that I don't use correctly the wildcards and bounds ... What's wrong ?
    Thanks

    Sorry not to really offer an actual explanation...I'm not sure I could get one right, so I'll leave that to an actual Expert!
    But here's another way of writing that example. It's maybe more heavyweight than what you want (and maybe also you'll get more replies telling you all the reason why it's a Bad Approach!), but it will compile for you.
    interface Strategy<S extends Strategy<S,C>, C extends Compound<S,C>>   {
            public abstract void apply(final Compound<S,C> c);
    abstract class Compound<S extends Strategy<S,C>, C extends Compound<S,C>> {
            Strategy<S,C> strategy;
            public void setStrategy(Strategy<S,C> strategy) {
                this.strategy = strategy;
            public final void move() {
                this.strategy.apply(this);
        }The basic idea is that Strategy and Compound define a way for two classes to relate to each other. If you declare classes XXX and YYY (respectively) to be a Strategy/Compound relationship, then you know that all of the business relating to Compound in XXX should actually be about YYY. It's just the same thing as knowing you get a String out of an Iterator<String>, except that it goes back and forth between two different classes. So your two concrete classes become:
    class AStrategy implements Strategy<AStrategy, ACompound> {
            public void apply(Compound<AStrategy, ACompound> compound) {
                return;
    class ACompound extends Compound<AStrategy, ACompound> {
            public ACompound(AStrategy strategy) {
                this.setStrategy(strategy); // BOOM !
        }Of course, overusing this leads to amazingly long type variable lists.

  • Class instantiation - and is this a pattern?

    Firstly, my apologies if my goal here is unclear. I am still learning the concepts and may perhaps have a lack of words for the appropriate terms or processes. Hopefully I can convey my meaning enough to get some feedback.
    I have a group of classes, all inheriting from a base class. My task is to add the functionality in these classes to another set of derived classes by simply creating instances of them in these classes constructor methods. To my knowledge this means the instance must take the class it's written in or (this) as it's parameter. My question is then really how should my external helper classes be written so they can be instanced in this way and is there a pattern that this idea conforms to and if so could someone explain this to me. My thanks in advance for any help, tips or directions to a good reference on this topic.

    It sounds a bit like the Strategy pattern.
    Your "helper" classes are providing various ways of performing a task on behalf of another class.
    AWT LayoutManagers implement strategies for laying out the Components in a Container. Have a look through that to see how it's done there.
    Whether your strategy classes need to take the "container" class in their constructor will depend on the functionality they provide. If their behaviour does not need to be cached then they could take a reference to the wrapper in each method call like LayoutManagers do.
    Hope this helps.

  • New(?) pattern looking for a good home

    Hi everyone, this is my second post to sun forums about this, I initially asked people for help with the decorator and strategy pattern on the general Java Programming forum not being aware that there was a specific section for design pattern related questions. Since then I refined my solution somewhat and was wondering if anyone here would take a look. Sorry about the length of my post, I know it's best to keep it brief but in this case it just seemed that a fully functional example was more important than keeping it short.
    So what I'd like to ask is whether any of you have seen this pattern before and if so, then what is it called. I'm also looking for some fresh eyes on this, this example I wrote seems to work but there are a lot of subtleties to the problem so any help figuring out if I went wrong anywhere is greatly appreciated. Please do tell me if you think this is an insane approach to the problem -- in short, might this pattern have a chance at finding a good home or should it be put down?
    The intent of the pattern I am giving below is to modify behavior of an object at runtime through composition. In effect, it is like strategy pattern, except that the effect is achieved by wrapping, and wrapping can be done multiple times so the effect is cumulative. Wrapper class is a subclass of the class whose instance is being wrapped, and the change of behavior is accomplished by overriding methods in the wrapper class. After wrapping, the object "mutates" and starts to behave as if it was an instance of the wrapper class.
    Here's the example:
    public class Test {
         public static void main(String[] args) {
              double[] data = { 1, 1, 1, 1 };
              ModifiableChannel ch1 = new ModifiableChannel();
              ch1.fill(data);
              // ch2 shifts ch1 down by 1
              ModifiableChannel ch2 = new DownShiftedChannel(ch1, 1);
              // ch3A shifts ch2 down by 1
              ModifiableChannel ch3A = new DownShiftedChannel(ch2, 1);
              // ch3B shifts ch2 up by 1, tests independence from ch3A
              ModifiableChannel ch3B = new UpShiftedChannel(ch2, 1);
              // ch4 shifts ch3A up by 1, data now looks same as ch2
              ModifiableChannel ch4 = new UpShiftedChannel(ch3A, 1);
              // print channels:
              System.out.println("ch1:");
              printChannel(ch1);
              System.out.println("ch2:");
              printChannel(ch2);
              System.out.println("ch3A:");
              printChannel(ch3A);
              System.out.println("ch3B:");
              printChannel(ch3B);
              System.out.println("ch4:");
              printChannel(ch4);
         public static void printChannel(Channel channel) {
              for(int i = 0; i < channel.size(); i++) {
                   System.out.println(channel.get(i) + "");
              // Note how channel's getAverage() method "sees"
              // the changes that each wrapper imposes on top
              // of the original object.
              System.out.println("avg=" + channel.getAverage());
    * A Channel is a simple container for data that can
    * find its average. Think audio channel or any other
    * kind of sampled data.
    public interface Channel {
         public void fill(double[] data);
         public double get(int i);
         public double getAverage();
         public int size();
    public class DefaultChannel implements Channel {
         private double[] data;
         public void fill(double[] data) {
              this.data = new double[data.length];
              for(int i = 0; i < data.length; i++)
                   this.data[i] = data;
         public double get(int i) {
              if(i < 0 || i >= data.length)
                   throw new IndexOutOfBoundsException("Incorrect index.");
              return data[i];
         public double getAverage() {
              if(data.length == 0) return 0;
              double average = this.get(0);
              for(int i = 1; i < data.length; i++) {
                   average = average * i / (i + 1) + this.get(i) / (i + 1);
              return average;
         public int size() {
              return data.length;
    public class ModifiableChannel extends DefaultChannel {
         protected ChannelModifier modifier;
         public void fill(double[] data) {
              if (modifier != null) {
                   modifier.fill(data);
              } else {
                   super.fill(data);
         public void _fill(double[] data) {
              super.fill(data);
         public double get(int i) {
              if(modifier != null)
                   return modifier.get(i);
              else
                   return super.get(i);
         public double _get(int i) {
              return super.get(i);
         public double getAverage() {
              if (modifier != null) {
                   return modifier.getAverage();
              } else {
                   return super.getAverage();
         public double _getAverage() {
              return super.getAverage();
    public class ChannelModifier extends ModifiableChannel {
         protected ModifiableChannel delegate;
         protected ModifiableChannel root;
         protected ChannelModifier tmpModifier;
         protected boolean doSwap = true;
         private void pre() {
              if(doSwap) { // we only want to swap out modifiers once when the
                   // top call in the chain is made, after that we want to
                   // proceed without it and finally restore doSwap to original
                   // state once ChannelModifier is reached.
                   tmpModifier = root.modifier;
                   root.modifier = this;
                   if(delegate instanceof ChannelModifier)
                        ((ChannelModifier)delegate).doSwap = false;
         private void post() {
              if (doSwap) {
                   root.modifier = tmpModifier;
              } else {
                   if(delegate instanceof ChannelModifier)
                             ((ChannelModifier)delegate).doSwap = true;
         public ChannelModifier(ModifiableChannel delegate) {
              if(delegate instanceof ChannelModifier)
                   this.root = ((ChannelModifier)delegate).root;
              else
                   this.root = delegate;
              this.delegate = delegate;
         public void fill(double[] data) {
              pre();
              if(delegate instanceof ChannelModifier)
                   delegate.fill(data);
              else
                   delegate._fill(data);
              post();
         public double get(int i) {
              pre();
              double result;
              if(delegate instanceof ChannelModifier)
                   result = delegate.get(i);
              else
                   result = delegate._get(i);
              post();
              return result;
         public double getAverage() {
              pre();
              double result;
              if(delegate instanceof ChannelModifier)
                   result = delegate.getAverage();
              else
                   result = delegate._getAverage();
              post();
              return result;
         public int size() {
              //for simplicity no support for modifying size()
              return delegate.size();
    public class DownShiftedChannel extends ChannelModifier {
         private double shift;
         public DownShiftedChannel(ModifiableChannel channel, final double shift) {
              super(channel);
              this.shift = shift;
         @Override
         public double get(int i) {
              return super.get(i) - shift;
    public class UpShiftedChannel extends ChannelModifier {
         private double shift;
         public UpShiftedChannel(ModifiableChannel channel, final double shift) {
              super(channel);
              this.shift = shift;
         @Override
         public double get(int i) {
              return super.get(i) + shift;
    Output:ch1:
    1.0
    1.0
    1.0
    1.0
    avg=1.0
    ch2:
    0.0
    0.0
    0.0
    0.0
    avg=0.0
    ch3A:
    -1.0
    -1.0
    -1.0
    -1.0
    avg=-1.0
    ch3B:
    1.0
    1.0
    1.0
    1.0
    avg=1.0
    ch4:
    0.0
    0.0
    0.0
    0.0
    avg=0.0

    jduprez wrote:
    Hello,
    unless you sell your design better, I deem it is an inferior derivation of the Adapter pattern.
    In the Adapter pattern, the adaptee doesn't have to be designed to support adaptation, and the instance doesn't even know at runtime whether it is adapted.
    Your design makes the "modifiable" class aware of the modification, and it needs to be explicitly designed to be modifiable (in particular this constrains the implementation hierarchy). Overall DesignPattern are meant to provide flexibility, your version offers less flexibility than Adapter, as it poses more constraint on the modifiable class.
    Another sign of this inflexibility is your instanceof checks.
    On an unrelated note, I intensely dislike your naming choice of fill() vs _fill()+, I prefer more explicit names (I cannot provide you one as I didn't understand the purpose of this dual method, which a good name would have avoided, by the way).
    That being said, I haven't followed your original problem, so I am not aware of the constraints that led you to this design.
    Best regards,
    J.
    Edited by: jduprez on Mar 22, 2010 10:56 PMThank you for your input, I will try to explain my design better. First of all, as I understand it the Adapter pattern is meant to translate one interface into another. This is not at all what I am trying to do here, I am trying to keep the same interface but modify behavior of objects through composition. I started thinking about how to do this when I was trying to apply the Decorator pattern to filter some data. The way I would do that in my example here is to write an AbstractChannelDecorator that delegates all methods to the Channel it wraps:
    public abstract class AbstractChannelDecorator implements Channel {
            protected Channel delegate;
    ...// code ommitted
         public double getAverage() {
              return delegate.getAverage();
    ...// code ommitted
    }and then to filter the data I would extend it with concrete classes and override the appropriate methods like so:
    public class DownShiftedChannel extends AbstractChannelDecorator {
         ...// code ommitted
         public double get(int i) {
              return super.get(i) - shift;
           ...// code ommitted
    }(I am just shifting the data here to simplify the examples but a more realistic example would be something like a moving average filter to smooth the data).
    Unfortunately this doesn't get me what I want, because getAverage() method doesn't use the filtered data unless I override it in the concrete decorator, but that means I will have to re-implement the whole algorithm. So that's pretty much my motivation for this, how do I use what on the surface looks like a Decorator pattern, but in reality works more like inheritance?
    Now as to the other points of critique you mentioned:
    I understand your dislike for such method names, I'm sorry about that, I had to come up with some way for the ChannelModifier to call ModifiableChannel's super's method equivalents. I needed some way to have the innermost wrapped object to initiate a call to the topmost ChannelModifier, but only do it once -- that was one way to do it. I suppose I could have done it with a flag and another if/else statement in each of the methods, or if you prefer, the naming convention could have been fill() and super_fill(), get() and super_get(), I didn't really think that it was that important. Anyway, those methods are not meant to be used by any other class except ChannelModifier so I probably should have made them protected.
    The instanceof checks are necessary because at some point ChannelModifier instance runs into a delegate that isn't a ChannelModifier and I have to somehow detect that, because otherwise instead of calling get() I'd call get() which in ModifiableChannel would take me back up to the topmost wrapper and start the whole call chain again, so we'd be in infinite recursion. But calling get() allows me to prevent that and go straight to the original method of the innermost wrapped object.
    I completely agree with you that the example I presented has limited flexibility in supporting multiple implementations. If I had two different Channel implementations I would need two ModifiableChannel classes, two ChannelModifiers, and two sets of concrete implementations -- obviously that's not good. Not to worry though, I found a way around that. Here's what I came up with, it's a modification of my original example with DefaultChannel replaced by ChannelImplementation1,2:
    public class ChannelImplementation1 implements Channel { ... }
    public class ChannelImplementation2 implements Channel { ... }
    // this interface allows implementations to be interchangeable in ChannelModifier
    public interface ModifiableChannel {
         public double super_get(int i);
         public double super_getAverage();
         public void setModifier(ChannelModifier modifier);
         public ChannelModifier getModifier();
    public class ModifiableChannelImplementation1
              extends ChannelImplementation1
              implements ModifiableChannel {
         ... // see DefaultChannel in my original example
    public class ModifiableChannelImplementation2
              extends ChannelImplementation1
              implements ModifiableChannel { ...}
    // ChannelModifier is a Channel, but more importantly, it takes a Channel,
    // not any specific implementation of it, so in effect the user has complete
    // flexibility as to what implementation to use.
    public class ChannelModifier implements Channel {
         protected Channel delegate;
         protected Channel root;
         protected ChannelModifier tmpModifier;
         protected boolean doSwap = true;
         public ChannelModifier(Channel delegate) {
              if(delegate instanceof ChannelModifier)
                   this.root = ((ChannelModifier)delegate).root;
              else
                   this.root = delegate;
              this.delegate = delegate;
         private void pre() {
              if(doSwap) {
                   if(root instanceof ModifiableChannel) {
                        ModifiableChannel root = (ModifiableChannel)this.root;
                        tmpModifier = root.getModifier();
                        root.setModifier(this);
                   if(delegate instanceof ChannelModifier)
                        ((ChannelModifier)delegate).doSwap = false;
         private void post() {
              if (doSwap) {
                   if(root instanceof ModifiableChannel) {
                        ModifiableChannel root = (ModifiableChannel)this.root;
                        root.setModifier(tmpModifier);
              } else {
                   if(delegate instanceof ChannelModifier)
                             ((ChannelModifier)delegate).doSwap = true;
         public void fill(double[] data) {
              delegate.fill(data);
         public double get(int i) {
              pre();
              double result;
              if(delegate instanceof ModifiableChannel)
    // I've changed the naming convention from _get() to super_get(), I think that may help show the intent of the call
                   result = ((ModifiableChannel)delegate).super_get(i);
              else
                   result = delegate.get(i);               
              post();
              return result;
         public double getAverage() {
              pre();
              double result;
              if(delegate instanceof ModifiableChannel)
                   result = ((ModifiableChannel)delegate).super_getAverage();
              else
                   result = delegate.getAverage();
              post();
              return result;
         public int size() {
              return delegate.size();
    public class UpShiftedChannel extends ChannelModifier { ...}
    public class DownShiftedChannel extends ChannelModifier { ... }

  • What is the best design pattern for this problem?

    No code to go with the question. I am trying to settle on the best design pattern for the problem before I code. I want to use an Object Oriented approach.
    I have included a basic UML diagram of what I was thinking so far. 
    Stated simply, I have three devices; Module, Wired Modem, and Wireless Modem.
    In the Device Under Test parent class, I have put the attributes that are variable from device to device, but common to all of them.
    In the child classes, I have put the attributes that are not variable to each copy of that device. The attributes are common across device types. I was planning to use controls in the class definition that have the data set to a default value, since it doesn't change for each serial number of that device. For example, a Module will always have a Device Type ID of 1. These values are used to query the database.
    An example query would be [DHR].[GetDeviceActiveVersions] '39288', 1, '4/26/2012 12:18:52 PM'
    The '1' is the device type ID, the 39288 is the serial number, and the return would be "A000" or "S002", for example.
    So, I would be pulling the Serial Number and Device Type ID from the Device Under Test parent and child, and passing them to the Database using a SQL string stored in the control of the Active Versions child class of Database.
    The overall idea is that the same data is used to send multiple queries to the database and receiving back various data that I then evaluate for pass of fail, and for date order.
    What I can't settle on is the approach. Should it be a Strategy pattern, A Chain of Command pattern, a Decorator pattern or something else. 
    Ideas?

    elrathia wrote:
    Hi Ben,
    I haven't much idea of how override works and when you would use it and why. I'm the newest of the new here. 
    Good. At least you will not be smaking with a OPPer dOOPer hammer if I make some gramatical mistake.
    You may want to look at this thread in the BreakPoint where i trie to help Cory get a handle on Dynamic Dispatching with an example of two classes that inherit from a common parent and invoke Over-ride VIs to do the same thing but with wildly varying results.
    The example uses a Class of "Numeric"  and a sibling class "Text" and the both implement an Add method.
    It is dirt simple and Cory did a decent job of explaining it.
    It just be the motivation you are looking for.
    have fun!
    Ben
    Ben Rayner
    I am currently active on.. MainStream Preppers
    Rayner's Ridge is under construction

  • Help with Strategy Pathern!

    Hello,
    I need to parse a very complex text file. If I keep all the parsing code in one file, it will be huge. Then I thought probably I can use strategy patthern to decouple it.
    "Another technique has a context pass itself as an argument, and the strategy request data from the context explicitly. "
    "Alternatively, the strategy can store a reference to its context, eliminating the need to pass anything at all. Either way, the strategy can request exactly what it needs"
    I want to use the way it mentioned in the GoF book, pass context or store a reference in the strategy, but.......don't know how to implement it :(
    Any help or code sample will be really appreciated!!!
    Thanks!

    I wrote the parsing program already, but everything is in a big class, more than 1000 lines.....It's not good, right?
    The program structure is like:
    Class parseFile {
    void parse () {
    file = readFile();
    line = file.readLine();
    flag = getFlag();
    switch (flag) {
    case 0:
    if line.startWith(...) then { .....}
    if line.startWith(...) then { .....}
    if line.startWith(...) then { .....}
    case 1:
    case 2:
    case 7:
    The structure is hard to maintain
    That's why I'm trying to use Strategy pattern to rewrite it.
    Any suggestions?
    Thanks!

Maybe you are looking for

  • No luck yet with failed to load core DL

    So I tried the trouble shooting steps to fix my issue, as explained on the site, but despite this my reader is still saying the same error message.

  • Vector art, resolution, and ID CS5

    Hey ID Gurus, I need your help. The job: 4-color process to be printed in Hong Kong The book: 90+ full-color diagrams created in Illustrator in CMYK. 200+ images, some shot in Camera Raw, others scanned in color. Photos will be converted to the CMYK

  • Employee payment related to expenses etc.

    Hello, Employee payment related to expenses etc. is done at company level.. Employee are treated as vendors. Expenses like: Newspaper exp. What kind of entry will be involve for this?what kind of GL will be required and how many GL? When we see emplo

  • Subselect in update

    Hello, i want to write an sql-update statement where a field through a part of another field will be supplemented. example: update tabelle set targetDirectiory = ' export/home/VALUE_FROM_FIELD x' where blablabla This should work as a subselect ?but I

  • Exchange 2013 Edge Transport install fails

    I'm trying to install the Edge Transport for Exchange 2013 but it gets to step 7 of 9: then give's the following error Error: The following error was generated when "$error.Clear();  new-ExchangeServer " was run: "Value cannot be null. Parameter name