jeudi 13 octobre 2016

Factory pattern: Accessing child methods

I have two classes CashStore and DrinkStore, both extends from Store. I have a StoreFactory class (returns Store object) to instantiate objects for clients. I want to access methods specific to child classes from these clients. How do I do it without casting? If I used casting, would it break the pattern, since now the clients know about the Child classes?

class Store
{
A(){}
B(){}
}

class CashStore{
A(){} B(){}
C(){} D(){} }

//impl for drink store and other stores

class StoreFactory{
public Store getStore(String type){
//return a Store obj based on type DrinkStore or CashStore
}


class Client{
StoreFactory fac;
public Client(){
fac = new StoreFactory();
Store s = fac.getStore("cash");
s.C(); //requires a cast
}
}

Does casting break my pattern?

Aucun commentaire:

Enregistrer un commentaire