Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Object Oriented Design; LinkedList and Stack

Tags:

java

stack

oop

list

I am writing a BFS and DFS in Java. What I was hoping to do was create one 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 perform BFS and DFS depending on how it is initialized. What is XXX? I don't think that it exists.

I thought that the entire point of object oriented programing is being able to do cool stuff like this.

What is the cleanest way to handle this?

like image 632
sixtyfootersdude Avatar asked Feb 15 '26 11:02

sixtyfootersdude


1 Answers

I think you're looking for the Strategy pattern. The way to do this is not Java specific, or other "cool stuff" for this matter. These types of things transcend languages.

To be more concrete, develop two more classes named BfsStrategy and DfsStrategy. Require that each class implement a certain Strategy interface. Use the class you posted to perform operations on them transparently. (Change class/interface names to be more suitable if you need to.)

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.
    }

}
like image 76
Mike Avatar answered Feb 17 '26 23:02

Mike