can you please give me the list of all type of patterns (architectural, design, etc.) used in Codoforum and FreiChat? Thank you.
mardi 2 juin 2015
Construct the name of the method to be called at runtime
I'm learning Java and I'm fairly new to this. Here is my problem with some pseudocode:
public void objectCaller(int objectNumber) {
switch(objectnumber) {
case 1:
object1.setFill(color.RED);
break:
case 2:
object2.setFill(color.RED);
break;
.
.and so on
}
}
Is there a way to replace it in a way with something like that?
public void objectCaller(int objectNumber) {
(object + objectnumber).setFill(color.RED);
}
It is not a concrete problem. I was just thinking about if it is possible to assemble the object names.
Singleton: how can destructor be called twice?
I asked a question about singleton implementation a few minutes ago, I've got very good answer from @LightnessRacesinOrbit.
But I cannot understand why in the next example if I instantiate Singleton in variable inst its destructor called twice?
#include <iostream>
class Singleton
{
public:
~Singleton() { std::cout << "destruction!\n"; }
static Singleton& getInstance()
{
static Singleton instance;
return instance;
}
void foo() { std::cout << "foo!\n"; }
private:
Singleton() { std::cout << "construction!\n"; }
};
int main()
{
Singleton inst = Singleton::getInstance();
inst.foo();
}
Output:
construction!
foo!
destruction!
destruction!
To be more correct, I understand why it is called twice. But I cannot understand how it can be called twice if after first destructor the instance of the class was destroyed? Why there is no exception?
Or it was not destroyed? Why?
Implementing Factory Pattern with reflection
I am implementing factory pattern Here is my factory class:
class ProductFactory
{
private HashMap m_RegisteredProducts = new HashMap();
public void registerProduct (String productID, Class productClass)
{
m_RegisteredProducts.put(productID, productClass);
}
public Product createProduct(String productID)
{
Class productClass = (Class)m_RegisteredProducts.get(productID);
Constructor productConstructor = cClass.getDeclaredConstructor(new Class[] { String.class });
return (Product)productConstructor.newInstance(new Object[] { });
}
}
and here is my concrete class:
class OneProduct extends Product
{
static {
Factory.instance().registerProduct("ID1",OneProduct.class);
}
...
}
My Question:
-
how do I enforce all the concrete implementations to register an ID along with their class object? - Because if the class doesn't register itself like this in the factory then it cant be used.
-
Can't I use an abstract class which requires somehow all its child to send its name and id to the parent, enforcing this constraint? Something like this:
public abstract class Product { public Product(String name, Class productClass){ } }
Am I missing anything here?
Triggering events from async/await functions in the right order
I have problems ensuring the order of events in my asynchronous task. The class from which other async tasks inherit has the following functions and takes the EventHandlers (ExecutionProgress, ExecutionStarted, ExecutionCompleted) in the constructor arguments:
public abstract Task Operation(IProgress<EventArgs> progress);
public virtual void Execute()
{
ExecuteAsync()
}
private void ReportProgress(EventArgs args)
{
if(ExecutionProgress != null) ExecutionProgress(this, args);
}
private async Task ExecuteAsync()
{
if(ExecutionStarted != null) ExecutionStarted(this, EventArgs.Empty)
await Operation(new Progress<EventArgs>(ReportProgress));
if(ExecutionCompleted != null) ExecutionCompleted(this, EventArgs.Empty)
}
Now in one of my classes, that inherits from asynchronous tasks, i override Operation with the following:
public override async Task Operation(IProgress<EventArgs> progress)
{
// run the synchronous function in another thread
JobResults results = await Task.Run(() => worker.DoYourJob());
progress.Report(results);
}
Running this code often, but not always, results in NullReference Exception in the ExecutionCompleted event handler when trying to access the JobResults. This is because ExecutionProgress event which writes the member variable usually gets fired after ExecutionCompleted for whatever reason. I think the standard says nothing about event ordering, but I'm looking for a nice solution to ensure deterministic ordering here. I want to fire ExecutionCompleted only after all ExecutionProgress events have been handled.
What would be a nice looking solution here? Is there any way to await until all progress reporting events have been handled.
how to get result which is returned with C callback in C++
I am rather new to handle C callbacks in C++. I made a sqlite wrapper c++ class, which just calls sqlite3_exec().
static int callback(void *NotUsed, int argc, char **argv, char **azColName){
SqliteAccessor* sqlite = static_cast<SqliteAccessor*> NotUsed;
if(argc > 0) {
sqlite->set_table_exists(true);
}
return 0;
}
class SqliteAccessor{
public:
bool has_table(const string dbName, const string tblName)
{
bool hasTable = false;
string sql;
sql = "SELECT " + quote_string(tblName) + "FROM " + quote_string(dbName)
+ "WHERE type = 'table' AND name = " + quote_string(tblName) + ";";
char *zErrMsg = 0;
int rc = sqlite3_exec(m_db, sql.c_str(), callback, (void*) this, &zErrMsg);
if( rc != SQLITE_OK ){
printf("SQL error: %s", zErrMsg);
sqlite3_free(zErrMsg);
}
return hasTable;
}
};
int caller(){
SqliteAccessor sqlite;
// to check if table exist
if (sqlite->has_table()){
// will above work or
// I should do with an extra call to query the changed state?
}
}
Now, I am quite confused how the caller can get the result from sqlite wrapper. I think, the caller cannot have the result by simply calling has_table(), because the result is returned from the callback, by set_table_exists(). So shall the caller get the result by making another call, e.g. call sqlite->get_table_exists() ?
Then this implies for every callback, I need to make a state in class SqliteAccessor, and a pair of set/get_table_exists(), which will be very cumbersome. How to design the class to make it nice to use by caller? Unfortunately, our code base does not support c++11.
Implementing a Command Design Pattern with static methods C#
I know how to implement a Command Design pattern as follows:
public abstract class Command
{
public abstract void Execute(string connectionString);
}
Say I inherit this ,as an example:
public class ConnectionCommand : Command
{
public override void Execute(string ConnectionString)
{
...do some stuff here...;
}
}
Problem is to use this ConnectionCommand I need to first instantiate an object, but the commands are context free, so I would prefer to not have to instantiate anything to run the ConnectionCommand's Execute method. (P.S. the ConnectionCommand.Execute() will be run from an event ,in a delegate).
How would I recreate this kind of design pattern but allowing the methods to be statically called?