I have C++ singleton implementation like this:
#include "DoingSomething.hpp"
class DoingSomething
{
static DoingSomething *shareInstance;
public:
int doSomething()
{
/*
*/
return someValue;
}
static DoingSomething *instance()
{
if (!shareInstance)
shareInstance = new DoingSomething;
return shareInstance;
}
};
But I want to access the singleton and the public functions inside of the singleton on my viewController using Objective-C. Any of you knows how can this be done?
I'll really appreciate your help.
Related
I am trying to implement a pattern in C++ where a nested private class inherits from the outer class and the private class is instantiated via a static factory method in the outer abstract class.
I have this code now, that compiles, but I am not sure whether I did it correctly.
Search.h:
namespace ns_4thex {
class Search {
private:
class Implementation;
public:
static Search & create();
virtual int doIt() = 0;
};
class Search::Implementation: public Search {
int doIt();
};
}
Search.cpp:
#include "Search.h"
using namespace ns_4thex;
Search & Search::create() {
return *(new Search::Implementation());
}
int Search::Implementation::doIt() {
return 0;
}
Thought?
A static factory method always returns a pointer type. So the create function should return a pointer or smart pointers in modern c++.
The declaration:
static std::unique_ptr<Search> create();
The definition:
std::unique_ptr<Search> Search::create() {
return std::make_unique<Search::Implementation>();
}
The complete code may like this:
#include <memory>
namespace ns_4thex {
class Search {
private:
class Implementation;
public:
static std::unique_ptr<Search> create();
virtual int doIt() = 0;
};
class Search::Implementation : public Search {
int doIt();
};
std::unique_ptr<Search> Search::create() {
return std::make_unique<Search::Implementation>();
}
int Search::Implementation::doIt() { return 0; }
} // namespace ns_4thex
Your example has potentially a memory leak. The factory pattern should return a pointer type instead of the reference type. The caller using it can free the allocated memory
Search* Search::create() {
return new Search::Implementation();
}
Say I have this code:
#include <iostream>
using namespace std;
class Something
{
int field1;
static Something *nill;
static bool initialized;
static void initialize() {
if (initialized)
return;
initialized = true;
}
public:
static Something* Nill()
{
initialize();
return nill;
}
static Something* Singleton(int field1)
{
initialize();
Something *ret = new Something();
ret->field1 = field1;
return ret;
}
}
Something* Something::nill = new Something();
bool Something::initialized = false;
int main(void)
{
Something *smth = something->Nill();
return 0;
}
Why isn't 'Something' a Singleton Class, and how could I make it one? Also how could I split this code into 2 files a .h and a .cpp? I had problems with that because I have some global variables here and I don't know how to use them in other files..
This is not a singleton class. Singleton class implies that in any given time you cannot have more than 1 instance of the class. In your example, you're not only creating a new instance but even return new class objects in its methods.
Make a default constructor protected (copy or move constructors too if you really want to be sure it's as singleton). Then use your static 'nill' as shown below:
class Something {
protected:
Something() = default;
...
int main() {
Something::nill->Nill();
...
P.s. Are you sure you need a singleton? Your methods say opposite.
First of all, I beg your pardon if this question has been already answered, but I simply cannot be sure of my choice.
I am working on a C++ game engine and I want it to be according to the modern standards. I wrote it in OOP manner and I have a main class called ENGINE. Inside it, there are a couple of class instances that represent specific subsystems: WINDOW, D3D11_RENDERER, etc. I also have a logging system (LOGGER) which must be available to all subsystems.
Now, this global access to the logger poses me a problem. I am uncertain whether I should declare it as static, outside the ENGINE class and have a function that returns a reference to it or instance it inside ENGINEand make all subsystems point to it.
To give you a better idea of what I am talking about, I posted simplified versions of these scenarios (take into account that I removed a lot of meaningless functions).
First solution:
class LOGGER {...};
LOGGER* GetLogger()
{
static LOGGER Logger;
return &Logger;
}
// Just one example.
class WINDOW
{
void Function()
{
GetLogger()->Write();
}
};
class ENGINE
{
private:
WINDOW Window;
}
Note that Irrlicht engine does it like this:
class Printer
{
public:
static void Write();
static LOGGER* Logger;
};
And it can be globally accessed like this:
os::Printer::Write();
Second solution:
class LOGGER() {...};
// Same example.
class WINDOW
{
public:
void Initialize(LOGGER* pLogger)
{
Logger = pLogger;
}
void Function()
{
Logger->Write();
}
private:
LOGGER* Logger;
};
class ENGINE
{
public:
void Initialize()
{
Window.Initialize(&Logger);
}
private:
WINDOW Window;
LOGGER Logger;
}
I do not know which is the best solution and I would be glad if you could point me to the right one. Thank you in advance.
I think this diagram represents better what you need:
Your components should be log-agnostic, as their function don't depend on logging capabilities. This function should be delegated to the engine.
The engine itself can contain a Logger component, which handles the de facto logging.
So let's see some basic code:
class Engine {
private:
Logger& mLogger;
EngineComponent mComponents[10];
public:
Engine(Logger& logger):
mLogger(logger) {
}
void addComponent(EngineComponent& c, int pos) {
mComponents[pos] = c;
c.setEngine(this);
}
void log(const std::string& message) {
mLogger.write(message);
}
}
class EngineComponent {
private:
Engine* mEngine;
protected:
EngineComponent() {}
public:
void setEngine(Engine* engine) {
mEngine = engine;
}
void log(const std::string& message) {
if (mEngine != NULL) {
mEngine->log(message);
}
}
}
class Window : public EngineComponent {
// add implementation
}
class D3d11Renderer : public EngineComponent {
// add implementation
}
class Logger {
protected:
Logger() {}
}
class FileLogger : public Logger {
// add implementation
}
Hope it helps.
I have this c# code:
class Animacion
{
private static Animacion instancia;
public static Animacion Instance
{
get
{
if (instancia == null)
{
instancia = new Animacion();
}
return instancia;
}
}
I want to convert that code to c++, I tryed to use a code converter from tangible software solutions and I got this:
//.h file code:
class Animacion
{
private:
static Animacion *instancia;
public:
static Animacion *getInstance() const;
};
//.cpp file code:
Animacion *Animacion::getInstance() const
{
if (instancia == nullptr)
{
instancia = new Animacion();
}
return instancia;
}
When I use the code generated from the converter I get errors like:
error: C2272: 'getInstance' : modifiers not allowed on static member functions
can anyone help me?
static Animacion *getInstance() const; get rid of the const. There's no point making a static class member function const in c++, hence the compiler error.
Also the established idiom for singletons in c++ looks rather like:
class Animacion {
private:
Animacion() {}
Animacion(const Animacion&) = delete;
Animacion& operator=(const Animacion&) = delete;
public:
static Animacion& getInstance() {
static Animacion theInstance;
return theInstance;
}
};
Further you should note, that Singleton is a really questionable design pattern, and you likely could live without it, in preference of an injected interface for the clients. That would help in decoupling implementation, from usage.
Arduino project. Using C++ 11 compiler. I have created an "interface" class, and several implementation classes. I want to implement stategy pattern. In my strategy manager class, I want to create an array of fixed length and initialize it in the constructor.
Java example of what I'm trying to do (and should be piece of cake in any modern language, right Stroustrup?)
public interface IState {
public void handle();
}
public class StateImpl implements IState {
#Override
public void handle(){
//Do something
}
}
public class StrategyManager {
private IState[] states;
public StrategyManager(){
states = new IState[3];
state[0] = new StateImpl();
state[1] = new StateImpl();
...
}
}
My first attempt in C++:
IState.h:
class IState {
public:
virtual ~IState() {}
virtual void handle() = 0;
};
StateImpl.h:
#ifndef StateImpl_h
#define StateImpl_h
#include "IState.h"
class StateImpl : public IState {
public:
StateImpl();
virtual void handle() override;
};
#endif
StateImpl.cpp:
#include "StateImpl.h"
StateImpl::StateImpl(){}
void StateImpl::handle(){
//Do something
}
So far it's ok. I've simplified my classes for brevity so the code might not compile, but mine's does, Now here comes the problem:
StrategyManager.h:
#ifndef StrategyManager_h
#define StrategyManager_h
#include "IState.h"
class StrategyManager {
private:
extern const IState _states[3];
public:
StrategyManager();
};
#endif
StrategyManager.cpp:
#include "StrategyManager.h"
StrategyManager::StrategyManager(){
IState _states[3] = {
new StateImpl(),
new StateImpl(),
new StateImpl()
};
}
This gives me all sort of errors:
error: storage class specified for '_states'
error: invalid abstract type 'IState' for '_states' because the following virtual functions are pure within 'IState':
virtual void IState::handle()
error: cannot declare field 'StrategyManager::_states' to be of abstract type 'IState'
since type 'IState' has pure virtual functions
... etc
So I have changed the array to hold pointers instead. In StrategyManager.h:
extern const IState* _states[3];
And now in StrategyManager.cpp constructor:
StrategyManager::StrategyManager(){
IState impl = new StateImpl(); //I hope this will be stored in the heap.
IState* _states[3] = {
&impl,
&impl,
&impl
};
}
But still got errors:
error: storage class specified for '_states'
error: cannot declare variable 'impl' to be of abstract type 'IState'
since type 'IState' has pure virtual functions
And on and on and on...
How can I do this in a simple way without using vectors or boost or any other fancy stuff? (Remember this is Arduino)
It's really much simpler than that, and closer to your java code (only showing relevant parts):
class StrategyManager {
private:
IState *_states[3];
public:
StrategyManager();
};
StrategyManager::StrategyManager(){
_states[0] = new StateImpl();
_states[1] = new StateImpl();
_states[2] = new StateImpl();
};
}
Just remember, C/C++ is not java, there's no GC so cleanup your objects