How to promote the design of many subclasses?

I have a parent class -Product

public abstract class Product {}

And 3 subclasses that extend it:

  • public class Vinyl extends Product {}

  • public class Book extends Product {}

  • public class Video extends Product {}

All subclasses override the method preview()with their specific implementation. Now I have a new design demand: I need to define a combo element vinyland book, which also has a method preview()(which is a combination> vinyl and books). In the instructions, he says that I can create a member of the interface field \ class or any implementation that I want to support, but I don’t know exactly how.

Will a new project also be implemented with inheritanceor change the current design?

+4
source share
2

?

. , . Product, VinylBook, . , , VinylVideo. ..

, . Composite . :

, , . .

a CompositeProduct

public class CompositeProduct` extends Product {
     private List<Product> products;

     public CompositeProduct(List<Product> products) { this.products = products }

     public String preview() {
          String previewText = "";
          for(Product product : products) { previewText+=product.preview(); }
          return preview;

     }
}

, , , - " " .

, " ":

Book book = new Book();
Vinyl vinyl = new Vinyl();
List<Product> products = new List<>();
products.add(book);
products.add(vinyl);
CompositeProduct vinylBook = new CompositeProduct(products);

Decorator, .

+5

, . ( , , Composite - , , Decorator, ).

, ( , ), ?

public abstract class Product {
    abstract void preview();
}

CompositeProduct , -

void preview(){
    for(Product product : products) product.preview();
}

, , .

- . , .

? - .

public interface Readable { void read(); }

public class Book extends Product implements Readable {}

? Showable

public interface Showable { void show(); }

public class Vinyl extends Product implements Showable {}

BookVinyl

public class BookVinyl extends Product implements Readable, Showable { }

? , BookVinyl , , , . ? , - .

0

Source: https://habr.com/ru/post/1648870/


All Articles