In my work i have a lot of discrepancy of opinions about UMLing class diagram of this sample factory:
class Program
{
private static TrainComponentsData _trainComponentsData;
static void Main(string[] args)
{
InitTrainComponentsData();
string str = _trainComponentsData.ToString();
}
private static void InitTrainComponentsData()
{
ITrainComponentsReader reader = TrainComponentsReaderFactory.Create("XML");
_trainComponentsData = reader.Read();
}
}
public class TrainComponentsReaderFactory
{
internal static ITrainComponentsReader Create(string readerType)
{
//....
}
}
internal class XMLTrainComponentsReader : ITrainComponentsReader
{
//....
}
public class TrainComponentsData
{
//....
}
internal interface ITrainComponentsReader
{
TrainComponentsData Read();
}
i just a little confused about various of difference diagrams:
etc...
thanks!
Related
I have class hierarchy as shown below. It's a simplified version of actual code.
class Base
{
public :
// user_define_type is a output parameter
virtual void Fill(user_define_type);
}
class A : public Base
{
public :
void Fill(user_define_type) override;
}
class B : public Base
{
public :
void Fill(user_define_type) override;
}
I am overriding Fill() method as I need different formatting in both derived classes. Now I have to write one more class deriving from "Base" as it has common functionality. Now my problem is that new class will have to implement Fill() that will operate on different user defined type. As I am returning base class pointer from factory so new Fill() has to be virtual in base but that means I have to add it's definition in older classes "A" and "B" and throw not supported exception from them. This is not a good design. Any better design you guys can suggest ? Thanks in advance.
I believe you need to create a common base class for your user_defined_types in order to achieve this. I also think this could be a good place to use the strategy pattern.
Basically, you create
class user_defined_type_base
{
...
}
class user_defined_type_derived : public user_defined_type_base
{
...
}
class DoSomething
{
private:
DoSomethingStrategy *strategy;
public:
DoSomething(DoSomethingStrategy *strategy) { this->strategy = strategy; }
void Fill(user_defined_type_base *type) { this->strategy->Fill(type); }
}
class DoSomethingStrategy
{
public:
virtual void Fill(user_defined_type_base *obj) = 0;
}
class DoSomethingStrategyA : public DoSomethingStrategy
{
public:
void Fill(user_defined_type_base *obj)
{
...
}
}
class DoSomethingStrategyB : public DoSomethingStrategy
{
public:
void Fill(user_defined_type_base *obj)
{
...
}
}
class DoSomethingStrategyC : public DoSomethingStrategy
{
public:
void Fill(user_defined_type_base *obj)
{
...
}
}
void main()
{
DoSomethingStrategy *strategy = new DoSomethingStragegyA();
DoSomething *dosomething = new DoSomething(strategy);
user_defined_type_base *type = new user_defined_type_base();
dosomething->Fill(type);
DoSomethingStrategy *strategyC = new DoSomethingStragegyC();
DoSomething *dosomethingC = new DoSomething(strategyC);
user_defined_type_base *typeC = new user_defined_type_derived();
dosomethingC->Fill(typeC);
}
I am using jackson ObjectReader and ObjectWriter object for serialization and deserialization in Akka Rest Server.
I am getting byteString in the request and deserialize it to object. Below is the scala code for it.
val a = objectReader.readValue[java.util.List[Base[Long]]](request.toArray)
Base class is an abstract class and I can have multiple implementation of it
#JsonTypeInfo(use = JsonTypeInfo.Id.NAME,
property = "impl")
#JsonSubTypes({
#JsonSubTypes.Type(value = A.class, name = "A")
})
public abstract class Base<T> implements Serializable {
private String impl;
private ResponseStatus status;
public String getImpl() {
return impl;
}
public void setImpl(String impl) {
this.impl = impl;
}
public void setStatus(ResponseStatus status) {
this.status = status;
}
public ResponseStatus getStatus() {
return status;
}
public static class ResponseStatus implements Serializable {
private ReturnCode code;
private String msg;
public void setCode(ReturnCode code) {
this.code = code;
}
public void setMsg(String msg) {
this.msg = msg;
}
public ReturnCode getCode() {
return code;
}
public String getMsg() {
return msg;
}
}
}
How ever I have observed that first call for readValue and writeValueAsBytes takes long.
I tried initializing it. But still it is not improving in Akka Execution Context. Anyone know the solution of it? Please help.
I am going through the difference between Abstract Factory Pattern vs Factory Method Pattern.
I understood that Factory Method is used to create one product only but Abstract Factory is about creating families of related or dependent products.
But how Factory method pattern uses inheritance while the abstract factory pattern uses composition is unclear for me.
I know that this is been asked couple of times, Could any one please explain with the below code how inheritance and composition is happening?
Factory Method code
class IRose
{
public:
virtual string Color(void)=0;
};
class RedRose: public IRose
{
public:
string Color(void)
{
return "Red";
}
};
class YellowRose: public IRose
{
public:
string Color(void)
{
return "Yellow";
}
};
class IFactory
{
public:
virtual IRose* Create(string type)=0;
//The factory create method in 90% of cases will take a parameter which
//determines what kind of the object the factory will return.
};
class Factory: public IFactory
{
public:
IRose* Create(string type)
{
if ("Red" == type)
return new RedRose();
if ("Yellow" == type)
return new YellowRose();
return NULL;
}
};
int main()
{
IRose* p = NULL;
IFactory* f = NULL;
f = new Factory(); //You have to create an INSTANCE of the factory
p = f->Create("Red");
cout<<"\nColor is: "<<p->Color()<<"\n";
delete p;
p = f->Create("Yellow");
cout<<"\nColor is: "<<p->Color()<<"\n";
delete p;
return 1;
}
Abstract factory code.
class IFridge
{
public:
virtual string Run(void) = 0;
};
class FridgeSamsung : public IFridge
{
public:
string Run(void)
{
return "You are now running Samsung Fridge\n";
}
};
class FridgeWhirlpool : public IFridge
{
public:
string Run(void)
{
return "You are now running Whirlpool Fridge\n";
}
};
class IWashingMachine
{
public:
virtual string Run(void) = 0;
};
class WashingMachineSamsung : public IWashingMachine
{
public:
string Run(void)
{
return "You are now running Samsung Washing Machine\n";
}
};
class WashingMachineWhirlpool : public IWashingMachine
{
public:
string Run(void)
{
return "You are now running Whirlpool Washing Machine\n";
}
};
class IFactory
{
public:
virtual IFridge* GetFridge(void) = 0;
virtual IWashingMachine* GetWashingMachine(void) = 0;
};
class FactorySamsung : public IFactory
{
IFridge* GetFridge(void)
{
return new FridgeSamsung();
}
IWashingMachine* GetWashingMachine(void)
{
return new WashingMachineSamsung();
}
};
class FactoryWhirlpool : public IFactory
{
IFridge* GetFridge(void)
{
return new FridgeWhirlpool();
}
IWashingMachine* GetWashingMachine(void)
{
return new WashingMachineWhirlpool();
}
};
int main()
{
IFridge* fridge; //Client just knows about fridge and washingMachine.
IWashingMachine* washingMachine; //and factory. He will write operations which
IFactory* factory; //work on fridges and washingMachines.
factory = new FactorySamsung;
//This is the only place where the client
//has to make a choice.
//The rest of the code below will remain same, even
//if the factory is changed. He can change the factory and the same range
//of products but from a different factory will be returned. No need to
//change any code.
fridge = factory->GetFridge();
cout << fridge->Run();
washingMachine = factory->GetWashingMachine();
cout << washingMachine->Run();
cout << "\n";
delete factory;
factory = new FactoryWhirlpool;
//See same client code.
fridge = factory->GetFridge();
cout << fridge->Run();
washingMachine = factory->GetWashingMachine();
cout << washingMachine->Run();
cout << "\n";
delete factory;
return 1;
}
This is a revised reply after some thought.
Factory Method: Usually, createObject() is a method of the Creator object.
Abstract Factory: Usually the Factory Object is an attribute of the Creator object.
Assume now that createObject() and Factory Object belong to their respective Creator.
Factory Method: createObject() may change in sub-classes of the Creator. This happens by changing the implementation of creatObject() via inheritance.
Abstract Factory: Factory Object may also change in sub-classes of the Creator. This change however happens by replacing one Factory Object with a different Factory Object ie the Creator object is changed by composition.
In your demo creatObject() and Factory Object are external to the Creator(s) so obscuring the distinction between composition/inheritance!
Christopher Okhravi has great youTube videos on patterns.
Factory Method https://www.youtube.com/watch?v=EcFVTgRHJLM&index=4&list=PLrhzvIcii6GNjpARdnO4ueTUAVR9eMBpc
Abstract Factory https://www.youtube.com/watch?v=v-GiuMmsXj4&index=5&list=PLrhzvIcii6GNjpARdnO4ueTUAVR9eMBpc
As requested here is a version of Factory Method (in C++ this time!).
If you need any assistance interpreting let me know.
class IRose
{
public:
virtual const char * Color(void) = 0;
};
class RedRose : public IRose
{
public:
const char * Color(void)
{
return "I am a Red rose";
}
};
class YellowRose : public IRose
{
public:
const char * Color(void)
{
return "I am a Yellow rose";
}
};
class RoseGarden
{
protected: class IRose* rose; // a pointer to the garden's rose
public:
virtual void createRose() { } // abstract Factory Method
public: void sayColor() {
cout << rose->Color() << '\n';
}
};
class RedRoseGarden : public RoseGarden
{
public:
void createRose()
{
this->rose = new RedRose(); // concrete factory method
}
};
class YellowRoseGarden : public RoseGarden
{
public:
void createRose()
{
this->rose = new YellowRose(); // concrete factory method
}
};
int main()
{
RoseGarden * garden = NULL;
garden = new YellowRoseGarden;
garden->createRose(); // correct factory method is chosen via inheritance
garden->sayColor();
delete garden;
garden = new RedRoseGarden;
garden->createRose(); // correct factory method is chosen via inheritance
garden->sayColor();
delete garden;
return 1;
}
Also here is a slightly modified version of Abstract Factory to better show how it is used. Just added a house object. Note I changed all your "string" objects to const char* for my compiler.
// make different types of fridges
class IFridge
{
public:
virtual const char* Run(void) = 0;
};
class FridgeSamsung : public IFridge
{
public:
const char* Run(void)
{
return "This house has a Samsung Fridge\n";
}
};
class FridgeWhirlpool : public IFridge
{
public:
const char* Run(void)
{
return "This house has a Whirlpool Fridge\n";
}
};
// make different types of washing machine
class IWashingMachine
{
public:
virtual const char* Run(void) = 0;
};
class WashingMachineSamsung : public IWashingMachine
{
public:
const char* Run(void)
{
return "This house has a Samsung Washing Machine\n";
}
};
class WashingMachineWhirlpool : public IWashingMachine
{
public:
const char* Run(void)
{
return "This house has a Whirlpool Washing Machine\n";
}
};
// make different type of factory
class IFactory
{
public:
virtual IFridge* GetFridge(void) = 0;
virtual IWashingMachine* GetWashingMachine(void) = 0;
};
class FactorySamsung : public IFactory
{
IFridge* GetFridge(void)
{
return new FridgeSamsung();
}
IWashingMachine* GetWashingMachine(void)
{
return new WashingMachineSamsung();
}
};
class FactoryWhirlpool : public IFactory
{
IFridge* GetFridge(void)
{
return new FridgeWhirlpool();
}
IWashingMachine* GetWashingMachine(void)
{
return new WashingMachineWhirlpool();
}
};
// Make a house object that has a fridge and a washing machine
class House
{
private:
class IWashingMachine * washingMachine;
class IFridge * fridge;
public:
House(IFactory * houseFactory) {
washingMachine = houseFactory->GetWashingMachine();
fridge = houseFactory->GetFridge();
}
void showAppliances() {
cout << washingMachine->Run();
cout << fridge->Run();
}
};
int main()
{
class IFactory * factory;
class House * house;
// make a samsung house
factory = new FactorySamsung;
house = new House(factory); // passing the factory by injection
house->showAppliances(); // now we have a Samsung house
cout << '\n';
// clean up
delete house;
delete factory;
// make a whirlpool house
factory = new FactoryWhirlpool;
house = new House(factory); // passing the factory by injection
house->showAppliances(); // now we have a WHilepool house
cout << '\n';
// clean up
delete house;
delete factory;
return 1;
}
I would like to implement a Abstract Factory pattern but also would like to be a singleton.
class WindowFactory {
protected:
virtual Scrollbar* createScrollbar() = 0;
};
class MacWindowFactory: public WindowFactory {
virtual Scrollbar* createScrollbar() {
//return a instance
}
;
};
class LinuxWindowFactory: public WindowFactory {
virtual ScrollBar* createScrollbar() {
//return a instance
}
;
};
Can someone help me with some sample code of making this Abstract Factory Singleton ?
Thanks in advance.
I managed to come up with more elegant solution ( No error checking as of now ). Kindly let me know your thoughts
#include<iostream>
#include<map>
class AbstractFactory
{
private:
typedef std::map< std::string, AbstractFactory* > ClientMap;
static ClientMap s_clientMap;
public:
void virtual createScrollbar() = 0;
void virtual createWindow() = 0;
static AbstractFactory* createInstance( std::string client );
protected:
void Register( std::string, AbstractFactory* );
};
AbstractFactory::ClientMap AbstractFactory::s_clientMap;
class LinuxFactory: public AbstractFactory
{
public:
void createScrollbar()
{
std::cout<<"Scrollbar for Linux"<<std::endl;
}
void createWindow()
{
std::cout<<"WIndow for Linux"<<std::endl;
}
private:
LinuxFactory()
{
Register( "Linux", this );
}
LinuxFactory( const LinuxFactory& );
static LinuxFactory s_LinuxFactory;
};
LinuxFactory LinuxFactory::s_LinuxFactory;
class MacFactory: public AbstractFactory
{
public:
void createScrollbar()
{
std::cout<<"Scrollbar for Mac"<<std::endl;
}
void createWindow()
{
std::cout<<"WIndow for Mac"<<std::endl;
}
private:
MacFactory()
{
Register( "Mac", this );
}
MacFactory( const MacFactory& );
static MacFactory s_MacFactory;
};
MacFactory MacFactory::s_MacFactory;
void AbstractFactory::Register( std::string clientName, AbstractFactory* factory )
{
s_clientMap.insert( ClientMap::value_type( clientName, factory ) );
}
AbstractFactory* AbstractFactory::createInstance( std::string client )
{
return s_clientMap.find( client )->second;
}
int main()
{
AbstractFactory *factory = AbstractFactory::createInstance( "Linux" );
factory->createScrollbar();
factory->createWindow();
}
If you need an actually dynamic abstract factory, you'd need to somehow set it up at run-time. You can do this by having a function selecting the desired factory with a suitable function which just sets up the actual singleton. In a real application you would probably have some sort of registration function where you can register functions getting an instance for the factory (factory factory functions). In the example below I used a simple set up where the available factories are known at compile time.
#include <memory>
#include <stdexcept>
#include <string>
class Scrollbar;
class WindowFactory {
public:
static void setFactory(std::string const&);
static Scrollbar* createScrollbar();
virtual ~WindowFactory() {}
private:
virtual Scrollbar* doCreateScrollbar() = 0;
};
class MacWindowFactory
: public WindowFactory {
friend void WindowFactory::setFactory(std::string const&);
virtual Scrollbar* doCreateScrollbar() {
return 0;
}
};
class LinuxWindowFactory
: public WindowFactory {
friend void WindowFactory::setFactory(std::string const&);
virtual Scrollbar* doCreateScrollbar() {
return 0;
}
};
// in WindowFactory.cpp
static std::auto_ptr<WindowFactory>& getPointer()
{
static std::auto_ptr<WindowFactory> pointer;
return pointer;
}
Scrollbar* WindowFactory::createScrollbar()
{
return getPointer().get()
? getPointer()->doCreateScrollbar()
: throw std::runtime_error("WindowFactory not set");
}
void WindowFactory::setFactory(std::string const& what)
{
if (what == "Mac") {
getPointer() = std::auto_ptr<WindowFactory>(new MacWindowFactory());
}
else if (what == "Linux") {
getPointer() = std::auto_ptr<WindowFactory>(new LinuxWindowFactory());
}
else {
throw std::runtime_error("unknown factory: '" + what + "'");
}
}
namespace WindowFactory {
Scrollbar* createScrollbar() {
#ifdef TARGET_OS_MAC
...
#elif __linux__
...
#endif
}
};
It's how I would've done it.
Hi,
I'm writing a component based class with a container, but after thinking of many different approaches, I can't find one that follows really what I want.
Here is an example of the general idea :
And the code I already wrote :
// Abstract class Component
class Component
{
public :
virtual ~Component() = 0;
virtual int GetResult() = 0;
};
class AddComponent : Component
{
public :
int GetResult() { return input1->GetResult() + input2->GetResult(); }
void SetInput1(Component* c) { input1 = c; }
void SetInput2(Component* c) { input2 = c; }
private :
Component* input1;
Component* input2;
};
class ConstComponent : Component
{
public :
int GetResult() { return value; }
void SetValue(int x) { value = x; }
private :
int value;
};
class SignComponent : Component
{
public :
int GetResult() { return sign(input->GetResult()); }
void SetInput(Component* c) { input = c; }
private :
Component* input;
};
class Container
{
public :
Container();
~Container();
void SetRootComponent(Component* c) { rootComponent = c; }
int GetResult() { return rootComponent->GetResult(); }
AddComponent* AddComponentAdd();
ConstComponent* ConstComponentAdd();
SignComponent* SignComponentAdd();
private :
Component* rootComponent;
std::vector<Component*> components;
};
void main(void)
{
// Create container
Container container = Container();
// Create components
SignComponent* cSign = container.AddComponentSign();
AddComponent* cAdd = container.AddComponentAdd();
ConstComponent* cConst1 = container.AddComponentConst();
ConstComponent* cConst2 = container.AddComponentConst();
// Link components
cSign->SetInput(cAdd);
cAdd->SetInput1(cConst1);
cAdd->SetInput2(cConst2);
cConst1->SetValue(-5);
cConst2->SetValue(3);
// Set root component for container
container.SetRootComponent(cSign);
// Compute
int result = container.GetResult();
}
This doesn't even compile, because of the cast of "XComponent" to "Component", which is abstract. I'm pretty sure there is a much better (and simpler ?) way to do it anyway, but I'm out of ideas.
The default inheritance for class is private:
class ConstComponent : Component
For all subclasses of Component you need public inheritance:
class ConstComponent : public Component
if you are attempting to insert new instances of the subclasses into the std::vector<Component*> (which I think you are).
private inheritance is not an is-a relationship, but is a has-a relationship. See How are "private inheritance" and "composition" similar? .