Java: object oriented design; LinkedList and stack

I am writing BFS and DFS in Java What I want to do is create a class like this:

/** Preforms BFS and DFS on ...
*/
public class Search{


  private XXX toSearch;
  // where XXX is an interface of Stack and LinkedList that has
  // remove() and add() methods.  

  public Search(boolean isBFS){
    if(isBFS)
      toSearch = new LinkedList();
    else
      toSearch = new Stack();
  }

  public void preformSearch(){
    while(toSearch.size() > 0){
      preformSearchOn(toSearch.remove());  // <----- KEY LINE
    }
  }

  private void preformSearchOn(...){...}

}

This class can execute BFS and DFS, depending on how it is initialized What is XXX? I don't think it exists

I think the whole point of object - oriented programming is to be able to do such cool things

What is the simplest way to deal with this problem?

Solution

I think you are looking for strategy pattern The way to do this is not Java specific or other "cool things" These types of things go beyond language

More specifically, develop two other classes called bfsstrategy and dfsstrategy Each class is required to implement a strategy interface Use your published classes to operate on them transparently (if necessary, it is more appropriate to change the class / interface name.)

For example:

public final class Seeker<E,K> {

    private final E structure;
    private final SearchStrategy strategy;

    public Seeker(final E aStructure,final SearchStrategy aStrategy) {
        structure = aStructure;
        strategy = aStrategy;
    }

    public boolean search(K aKey) {
        return strategy.search(structure,key); //Pretty generic.
    }

}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>