Is the observer design pattern already defined in STL (Like the java.util.Observer and java.util.Observable in Java) ?
No, but Boost.Signals2 gives you something similar.
As far as my knowledge goes in C++, STL doesn't have an implementation for Observer pattern. There was a proposal for Signal/Slot for standard library in TR2 though.
There are plenty of libraries which provides implementation for Observer pattern Qt library being one of the pioneers. The boost library has an implementation (see Boost::Signals & Boost::Signals2).
The Poco C++ library has a neat implementation of the observer pattern (see NotificationCenter).
libsigc++, cpp-events are some of the other libraries that provide signal/slot implementations.
No it doesn't. The C++ STL is much smaller than Java's Standard Library. If you are looking for something to expand on the STL that is supported by almost everything, it would be worth taking a look at the Boost libraries. In this case you may want to look at Boost.Signals which provides a signal/slot model.
Here is a reference implementation (from Wikipedia).
#include <iostream>
#include <string>
#include <map>
#include <boost/foreach.hpp>
class SupervisedString;
class IObserver{
public:
virtual void handleEvent(const SupervisedString&) = 0;
};
class SupervisedString{ // Observable class
std::string _str;
std::map<IObserver* const, IObserver* const> _observers;
typedef std::map<IObserver* const, IObserver* const>::value_type item;
void _Notify(){
BOOST_FOREACH(item iter, _observers){
iter.second->handleEvent(*this);
}
}
public:
void add(IObserver& ref){
_observers.insert(item(&ref, &ref));
}
void remove(IObserver& ref){
_observers.erase(&ref);
}
const std::string& get() const{
return _str;
}
void reset(std::string str){
_str = str;
_Notify();
}
};
class Reflector: public IObserver{ // Prints the observed string into std::cout
public:
virtual void handleEvent(const SupervisedString& ref){
std::cout<<ref.get()<<std::endl;
}
};
class Counter: public IObserver{ // Prints the length of observed string into std::cout
virtual void handleEvent(const SupervisedString& ref){
std::cout<<"length = "<<ref.get().length()<<std::endl;
}
};
int main(){
SupervisedString str;
Reflector refl;
Counter cnt;
str.add(refl);
str.reset("Hello, World!");
std::cout<<std::endl;
str.remove(refl);
str.add (cnt);
str.reset("World, Hello!");
std::cout<<std::endl;
return 0;
}
#include <iostream>
#include <string>
#include <set>
using namespace std;
class Subject;
class Observer {
public:
virtual void update(Subject & subject) = 0;
};
// also knows as Observable in literature
class Subject
{
string state;
set<Observer*> observers;
public:
void attachObserver(Observer *o) { observers.insert(o); }
void detachObserver(Observer *o) { observers.erase(o); }
void notifyObservers()
{
for (auto &o : observers)
{
o->update(*this);
}
}
string getState() { return state; }
void changeState(const string & s)
{
state = s;
notifyObservers();
}
};
class ObserverImpl : public Observer
{
string state;
public:
void update(Subject & sbj) override
{
state = sbj.getState();
}
string getState() { return state; }
};
int main()
{
ObserverImpl a, b, c;
Subject subject;
subject.attachObserver(&a);
subject.attachObserver(&b);
subject.attachObserver(&c);
subject.changeState("Observer pattern");
cout << a.getState() << endl;
cout << b.getState() << endl;
cout << c.getState() << endl;
return 0;
}
please also see UML/flow diagrams http://codepatterns.ddns.net/
The Observer design pattern is not defined in the STL. You can refer to the "Gang of four" Design Patterns book or a Google search should provide enough details to implement it. If this question isn't answered soon, I'll post a quick example.
#include<iostream>
#include<string.h>
#include<vector>
#include<algorithm>
using namespace std;
class Customer;
class flipkart
{
vector<Customer*>list;
vector<Customer*>::iterator it;
public:
void Register(Customer *customer)
{
list.push_back(customer);
}
void unregister(Customer *customer)
{
list.erase(remove(list.begin(), list.end(),customer), list.end());
}
void notify(string item,float vprice);
};
class observer
{
public:
virtual void update(string item,float vprice)=0;
};
class Customer:public observer
{
string name;
public:
Customer(string n)
{
name=n;
}
void update(string item,float vprice)
{
cout<<"**Flipkart**updated price for "<<item<<" is:"<<vprice<<" Rupees only, request recieved by "<<name<<endl;
}
};
void flipkart::notify(string item,float vprice)
{
for(it=list.begin();it!=list.end();it++)
{
(*it)->update(item,vprice);
}
}
class product:public flipkart
{
public:
void change_price(string item,float vprice)
{
notify(item,vprice);
}
};
int main()
{
Customer customer1("Dhoni"),customer2("Yuvraj"),customer3("Kohli");
product LCD;
LCD.Register(&customer1);
LCD.Register(&customer2);
LCD.Register(&customer3);
LCD.change_price("LCD HD2 TV",12000);
LCD.unregister(&customer2);
cout<<"after unregisterng customer2:\n";
LCD.change_price("LCD HD2 TV",11500);
}
Related
I am using c++11 compiler.
I have two classes - class Test and class TestHelper.
The class Test is a friend-to-class TestHelper.
The class Test is only which we can access from outside.
Now, we want to call Test API i.e. setVal(). This setVal() should call
Test2 API i.e. setX and is expecting this pointer. I don't want to use this pointer but want
to use a smart pointer instead. How can I do so?
The notion of this kind of desirability is because of the fact that in reality, my class Test is pretty big. So, I am trying to make a helper class for Test i.e.
class TestHelper;
class Test
{
friend class TestHelper;
int x;
public:
void display() {
std::cout << x;
}
void setVal(int val) {
TestHelper testH;
testH.setX(this, 324);
}
};
class TestHelper
{
public:
void setX(Test *test, int val) {
/** some algorithm here and then change val to something else */
test->x = val*100;
}
};
int main()
{
std::cout << "Hello World!\n";
Test x;
x.setVal(130);
}
I tried changing the prototype from void setX(Test *test, int val)
to void setX(std::shared_ptr<Test> test, int val) but don't know how to pass this pointer
as std::shared_ptr<Test> test here.
So here is working solution with shared pointers. The example doesn't even compile due to missing definitions so you have to restructure your code into headers and cpp files.
Test.h:
#ifndef TEST_H
#define TEST_H
#include <memory>
#include "TestHelper.h"
class Test : public std::enable_shared_from_this<Test>
{
private:
friend class TestHelper;
int x;
public:
void display();
void setVal(int val);
};
#endif
Test.cpp:
#include <iostream>
#include "Test.h"
void Test::display() {
std::cout << x;
}
void Test::setVal(int val) {
TestHelper testH;
testH.setX(shared_from_this(), 324);
}
TestHelper.h:
#ifndef TESTHELPER_H
#define TESTHELPER_H
class Test;
class TestHelper
{
public:
void setX(std::shared_ptr<Test> test, int val);
};
#endif
TestHelper.cpp:
#include <memory>
#include "TestHelper.h"
#include "Test.h"
void TestHelper::setX(std::shared_ptr<Test> test, int val) {
/** some algorithm here and then change val to something else */
test->x = val*100;
}
main.cpp:
#include <iostream>
#include <memory>
#include "Test.h"
int main(void){
std::cout << "Hello World!\n";
auto x = std::make_shared<Test>();
x->setVal(130);
x->display();
}
You can run it here: https://paiza.io/projects/e/79dehCx0RRAG4so-sVZcQw
I don't understand why you want this, here's a few variants that compile
reference
// Reference variant
#include <iostream>
class Test;
class TestHelper
{
public:
void setX(Test & test, int val);
};
class Test
{
friend class TestHelper;
int x;
public:
void display() {
std::cout << x;
}
void setVal(int val) {
TestHelper testH;
testH.setX(*this, 324);
}
};
void TestHelper::setX(Test &test, int val)
{
/** some algorithm here and then change val to something else */
test.x = val*100;
}
int main()
{
Test x;
x.setVal(130);
x.display();
}
http://cpp.sh/7t3ec
shared ptr
// Shared ptr variant
#include <iostream>
#include <memory> // Required for shared_ptrs
class Test;
class TestHelper
{
public:
void setX(std::shared_ptr<Test> test, int val);
};
class Test : public std::enable_shared_from_this<Test>
{
friend class TestHelper;
int x;
public:
void display() {
std::cout << x;
}
void setVal(int val) {
TestHelper testH;
testH.setX(shared_from_this(), 324);
}
};
void TestHelper::setX(std::shared_ptr<Test> test, int val)
{
/** some algorithm here and then change val to something else */
test->x = val*100;
}
int main()
{
auto x = std::make_shared<Test>(); // x needs to be created as shared_ptr or it won't work
x->setVal(130);
x->display();
}
http://cpp.sh/87ao2
Perhaps with these you can refine your question?
I'm trying to implement a C++ factory class that also perform the self registration of some derived classes. My implementation is based on the library:
http://arcticinteractive.com/2008/10/06/boost-centric-factory-pattern-implementation/
that is based on the Boost library. Just to give you a quick overview of this library, here is a simple self-explained (I hope) example:
struct foo { virtual ~foo() {} };
struct bar : foo { bar(int i) { std::cout << "bar() " << i << "\n"; } };
struct baz : foo { baz(int i) { std::cout << "baz() " << i << "\n"; } };
...
typedef factory< foo*(int) > myfactory_t;
myfactory_t f;
// Register a default (operator new) creator function
// for an implementation type
register_new_ptr<bar>(f, "bar");
register_new_ptr<baz>(f, "baz");
// Create objects through the factory
foo* fooimpl1 = f["bar"](1234);
foo* fooimpl2 = f["baz"](4321);
What I'm trying to do is to delegate each class to self-register them self to the factory using a static method. Here is the code:
animal.h
#pragma once
#include <cstring>
#include <iostream>
#include "factory.hpp"
#include "abstract_factory.hpp"
class zoo;
using namespace std;
using namespace boost::factory;
class animal{
virtual const std::string do_sound() const = 0;
std::string name_;
int age_;
zoo* myZoo_;
public:
animal(const std::string& name, int age, zoo* myZoo) : name_(name), age_(age), myZoo_(myZoo)
{}
virtual ~animal() {}
const std::string sound() const
{
return do_sound();
}
const std::string& name() const { return name_; }
const int age() const { return age_; }
};
template <class T>
struct animalFactory{
typedef factory< animal*(std::string&, int, zoo*) > myfactory_t;
static const myfactory_t* f;
static bool registerAnimal(const std::string& animalname){
return register_new_ptr<T>(&f, animalname);
};
};
When I try to register a class like:
crocodile.cpp
#include "crocodile.h"
bool r = animalFactory<crocodile>::registerAnimal("crocodile");
I get an error from visual studio 2012 that is:
animal.h(41): error C2893: Failed to specialize function template 'bool boost::factory::register_new_ptr(Factory &,Factory::id_param_type)'
Could someone help me to understand what is going on here? Thanks a lot!
I already asked about my Problem, now I'm on the next Step. In the code below I have the Problem, that I always have to make the EventHandler (Server::HandleMessage) static. But I need to have it non static to access other Variables in the Server class from within the Handler.
How can I achieve this?
Here my Code:
#include <iostream>
#include <functional>
using namespace std;
class Client{
public:
struct MessageReceiveArgs {
MessageReceiveArgs(int ID, const std::string& Text) : ID(ID), Text(Text) {}
int ID;
std::string Text;
};
std::function<void(MessageReceiveArgs)> onMessageReceive;
Client(){}
void FireEvent(){
this->onMessageReceive(MessageReceiveArgs(16, "SomeText"));
}
};
class Server{
public:
int i;
Server(){
this->client.onMessageReceive = &Server::HandleMessage;
this->i = 5;
}
void FireEvent(){
this->client.FireEvent();
}
Client client;
static void HandleMessage(Client::MessageReceiveArgs args) {
std::cout<<"ID "<<args.ID<<": "<<" "<<args.Text<<std::endl;
//need it non static
//std::cout<<"I: "<<this->i<<std::endl;
}
};
int main() {
Server sv = Server();
sv.FireEvent();
}
As mentioned in my earlier Post, i'm new to Standard C++ (Unix).
I'm fairly sure this is what you're after. You need to bind the implicit this explicitly when invoking a pointer-to-member through std::function in the fashion you seem to desire.
#include <iostream>
#include <functional>
using namespace std;
class Client{
public:
struct MessageReceiveArgs
{
MessageReceiveArgs(int ID, const std::string& Text)
: ID(ID), Text(Text) {}
int ID;
std::string Text;
};
Client(){}
void FireEvent()
{
this->onMessageReceive(MessageReceiveArgs(16, "SomeText"));
}
std::function<void(MessageReceiveArgs)> onMessageReceive;
};
class Server
{
public:
int i;
Server()
{
this->client.onMessageReceive
= std::bind(&Server::HandleMessage, this, std::placeholders::_1);
this->i = 5;
}
void FireEvent()
{
this->client.FireEvent();
}
Client client;
void HandleMessage(Client::MessageReceiveArgs args)
{
std::cout<<"ID "<<args.ID<<": "<<" "<<args.Text<<std::endl;
}
};
int main()
{
Server sv = Server();
sv.FireEvent();
}
Output
ID 16: SomeText
main:
#include <iostream>
#include <string>
#include "serviceChargeChecking.h"
int main()
{
serviceChargeChecking newAccount("Crim", 111222, 50.00, 100, 1.00);
system("PAUSE");
return 0;
}
serviceChargeChecking.h:
#ifndef H_serviceChargeChecking
#define H_serviceChargeChecking
#include "checkingaccount.h"
#include <string>
class serviceChargeChecking: public checkingAccount
{
public:
void setMonthlyFee(double);
void writeCheck(int);
void getMonthlyStatement() const;
serviceChargeChecking(std::string =" ",int = 0, double = 0.00, int= 0, double = 0.00);
private:
double serviceCharge;
};
#endif
serviceChargeChecking.cpp:
#include "serviceChargeChecking.h"
#include <iostream>
using std::string;
void serviceChargeChecking::setMonthlyFee(double fee)
{
serviceCharge=fee;
}
void serviceChargeChecking::getMonthlyStatement() const
{
checkingAccount::getMonthlyStatement();
std::cout<< "Service Charge: " << serviceCharge << std::endl;
}
void serviceChargeChecking::writeCheck(int ammount)
{
if(checkingAccount::getChecks()>0)
{
checkingAccount::setChecks(checkingAccount::getChecks()-ammount);
}
else
{
std::cout<<"No checks available." << std::endl;
}
}
serviceChargeChecking::serviceChargeChecking(string name, int acct, double bal, int numCheck, double sCharge)
{
bankAccount::setAcctOwnersName(name);
bankAccount::setAcctNum(acct);
bankAccount::setBalance(bal);
checkingAccount::setChecks(numCheck);
serviceCharge=sCharge;
}
checkingAccount.h:
#ifndef H_checkingAccount
#define H_checkingAccount
#include "bankAccount.h"
#include <iostream>
class checkingAccount: public bankAccount
{
public:
virtual void writeCheck()=0;
void deposit(double);
void withdraw(double);
void getMonthlyStatement() const;
int getChecks();
void setChecks(int);
private:
int numChecks;
};
#endif
checkingAccount.cpp:
#include "checkingAccount.h"
#include <iostream>
int checkingAccount::getChecks()
{
return numChecks;
}
void checkingAccount::setChecks(int c)
{
numChecks=c;
}
void checkingAccount::deposit(double d)
{
bankAccount::setBalance(bankAccount::getBalance()+d);
}
void checkingAccount::withdraw(double w)
{
bankAccount::setBalance(bankAccount::getBalance()-w);
}
void checkingAccount::getMonthlyStatement() const
{
bankAccount::getMonthlyStatement();
}
bankAccount.h:
#ifndef H_bankAccount
#define H_bankAccount
#include <string>
class bankAccount
{
public:
std::string getAcctOwnersName() const;
int getAcctNum() const;
double getBalance() const;
void getMonthlyStatement() const;
void setAcctOwnersName(std::string);
void setAcctNum(int);
void setBalance(double);
virtual void withdraw(double)=0;
virtual void deposit(double)=0;
private:
std::string acctOwnersName;
int acctNum;
double acctBalance;
};
#endif
bankAccount.cpp:
#include "bankAccount.h"
#include <iostream>
using std::string;
string bankAccount::getAcctOwnersName() const
{
return acctOwnersName;
}
int bankAccount::getAcctNum() const
{
return acctNum;
}
double bankAccount::getBalance() const
{
return acctBalance;
}
void bankAccount::setAcctOwnersName(string name)
{
acctOwnersName=name;
}
void bankAccount::setAcctNum(int num)
{
acctNum=num;
}
void bankAccount::setBalance(double b)
{
acctBalance=b;
}
void bankAccount::getMonthlyStatement() const
{
std::cout << "Name on Account: " << getAcctOwnersName() << std::endl;
std::cout << "Account Id: " << getAcctNum() << std::endl;
std::cout << "Balance: " << getBalance() << std::endl;
}
I know this is a lot of code to go through but can anyone help me understand why i cannot create an object from the class serviceChargeChecking the error is telling me that i cannot create an object from the abstract class but it doesn't seem to be abstract to me.
serviceChargeChecking implements void writeCheck(int), but the pure virtual function from checkingAccount has type void writeCheck(), so it's still pure in serviceChargeChecking, which makes the class abstract.
You have this in the abstract class checkingAccount:
virtual void writeCheck()=0;
but implement this in the derived class serviceChargeChecking:
void writeCheck(int);
The signature must be the same.
The writeCheck() method has different signatures in serviceChargeChecking and checkingAccount.
If you use C++11, use override in order to avoid this kind of error.
It's because your CheckingAcount has writeCheck() and serviceChargeChecking has writeCheck(int);
This probably due to the fact that you failed to Override checkingAccount's, writeCheck method, the abstract prototype was was
in checkingAccount class
virtual void writeCheck()=0;
and in serviceChargeChecking class
void writeCheck(int);
note the parameters, you didn't override checkingAccount's writeCheck you probably inherited it (implicitly), the serviceChargeChecking made a new writeCheck with an int parameter.
I have made a map of functions. all these functions are void and receive single string parameter.
code:
void f1(string params){...}
void f2(string params){...}
void f3(string params){...}
map<string , void*> funcMap;
funcMap["f1"] =(void*)&f1;
funcMap["f2"] =(void*)&f2;
funcMap["f3"] =(void*)&f3;
how do i call a function?
I tried the next code, but id doesn't work:
void (*func)(string) = &funcMap[commandType];
func(commandParam);
I get this error message:
Server.cpp:160:46: error: cannot convert ‘void**’ to ‘void (*)(std::string) {aka void (*)(std::basic_string<char>)}’ in initialization
using pfunc = void (*)(string);
map<string, pfunc> funcMap;
funcMap["f1"] = f1; //and so forth
And then call:
pfunc f = funcMap[commandType];
(*f)(commandParam);
In general, why throw away type safety? If it's a map of function pointers, declare it to be one.
Why not just have those as separate classes.
Then have the methods as virtual.
You can then have a map between the string and the base class.
i.e.
class Someoperation
{
virtual void Doit() = 0;
};
map<string, Someopertion> ops;
Then
class MyOp : public Someoperation
{
void Doit() { /* Some code here */}
};
Just add objects
ops["Hello"] = MyOp();
then call it
ops["Hello"].Doit();
&funcMap[commandType]
Just drop the &. Your compile error was useful here. It had a void** on the right which is because you took the address of a function pointer. You don't want two levels of indirection there.
Try C++ style. It has overhead for allocation and inheritance, but it's more flexible and extensible if you'll need some more functionality in the future.
#include <iostream>
#include <string>
#include <unordered_map>
#include <memory>
using namespace std;
class Someoperation {
public:
virtual void Doit() = 0;
};
class MyOp1 : public Someoperation {
public:
void Doit() final { cout << "MyOp1" << endl; }
};
class MyOp2 : public Someoperation {
public:
void Doit() final { cout << "MyOp2" << endl; }
};
int main() {
unordered_map<string, unique_ptr<Someoperation> > ops;
ops["1"] = unique_ptr<Someoperation>(new MyOp1);
ops["2"] = unique_ptr<Someoperation>(new MyOp2);
ops["1"]->Doit(); // Out: MyOp1
ops["2"]->Doit(); // Out: MyOp2
return 0;
}