samedi 31 octobre 2015

Design Pattern for relation ship between menus and other part of application

i am looking for this article but not able to find it any where Use Design Patterns to Simplify the Relationship Between Menus and Form Elements in .NET. It looks like MSDN has removed it? Does any one know where i can find it?

Actually i am looking for a Design pattern that i can use for relation ship between menu and other part of application.

When should you really use the visitor pattern

Ok before marking this as a duplicate let me clarify myself. I'm reading about the visitor pattern and its applicable uses.

I've stumbled upon this post: When should I use the Visitor Design Pattern?

and the user who wrote the first answer says as follow :

Now we want to add a new operation to the hierarchy, namely we want each animal to make its sound. As far as the hierarchy is this simple, you can do it with straight polymorphism:
...
But proceeding in this way, each time you want to add an operation you must modify the interface to every single class of the hierarchy.

Now, I mostly see why it's needed from his perspective, it's basically a way to cut compilation time by making it so not every time you want to add a new polymorphic method to a class hierarchy, the whole hierarchy will get recompiled.

But he's also saying that it's fine adding a new polymorphic method to the hierarchy as long as it's a "simple" hierarchy. But my question is when do you set your line and decide on what is simple and what is not.
Also, what if an hierarchy is a complex one, but adding a new method just make total sense to be and instance method rather than having the operation in a complete different class ?

Searching a bit more I found this article explaining the visitor pattern and it's uses http://ift.tt/1iuUqTl

The author gave an example where writing an instance method makes the object coupled to something and moving the method to a different class (The visitor) breaks the decoupling. This made more sense to me, but I'm still not quite sure when this pattern should really be used, the first argument of "changing the hierarchy time every time you want to add a new polymorphic method..." seems to me like an excuse because if a method seems to fit in the hierarchy it should be there logically, Assuming the Animal example was a really complex hierarchy and I would have decided to add make sound method, adding an instance method would be a logical choice (in my mind).
But maybe I'm wrong so I'm here asking for more insight about this, maybe someone could enlighten me.

Game of Life, combining JButtons with Observer Pattern

I'm coding the Game of Life in Java for School. My Grid contains Cells, every Cell has a corresponding Button. The Button shows the current condition of every Cell by its Colour. To "combine" the Button and the Cell, I have to use the Observeable Pattern. I have some troubles with using it and can't figure out what I am doing wrong

This is the part of my Cell-Class where I change the value (condition - live or dead) of the Cell. public void setValue(boolean value) { setChanged(); this.value = value; notifyObservers(value); }

The Button should Observe the Cell, so here is the code of my Button Class:

public class MyJButton implements Observer {

private JButton b1;


public JButton setb1(boolean condition){
    this.b1 = new JButton("");
    if (condition == true){
    this.b1.setBackground(Color.WHITE);
    }
    if (condition == false){
        this.b1.setBackground(Color.BLACK);
    }
    this.b1.setBorder( BorderFactory.createRaisedBevelBorder() );
    this.b1.setPreferredSize(new Dimension(10, 10));

    return this.b1;
}



@Override
public void update(Observable arg0, Object arg1) {
    boolean condition = (boolean)arg1;
    if (condition == true){
        this.b1.setBackground(Color.WHITE);
    }
    if (condition == false){
    this.b1.setBackground(Color.BLACK);
    }
}

}

In my GUI Class I add all the Buttons to my GUI and make them observe the Cells.

    public MyJButton[] CellButton;
public void initField() {
    // Creating panel for buttons, which correspond to cells
    cellPanel.removeAll();
    cellPanel.setLayout(new GridLayout(grid.getRows(), grid.getCols()));
    cellPanel.setPreferredSize(new Dimension(size * grid.getCols(), size * grid.getRows()));
    cellPanel.setBackground(Color.BLACK);

    int i;
    int j;
    int x = 0;
    for (i = 0; i < grid.getCols(); i ++){
        for (j = 0; j < grid.getRows(); j++){

            CellButton = new MyJButton[(grid.getRows() * grid.getCols())];
            CellButton[x] = new MyJButton();
            grid.getCell(j, i).addObserver(CellButton[x]);
            cellPanel.add(CellButton[x].setb1(true), BorderLayout.CENTER);
            x++;
        }
        j = 0;
    }       

    //TODO Add the Observer Pattern here 
    //Buttons have to be added to the GUI and connected with the Cell 
    //Use the observer interface of java 

    frame.add(cellPanel, BorderLayout.WEST);
    cellPanel.updateUI();
    frame.pack();
    frame.setVisible(true);
}

Then I tried to Change one Cell (and therefore a Button) to another condition

        this.cellgrid[3][3].setValue(false);

but it didnt work out at all. Maybe someone could help my that would be very kind.

Thanks, Lars.

Smarter way to write my newbie repetitive PHP?

Hi there please forgive me I've just managed to cobble this together and I think a more advanced programmer could give me a hint or two on a programming technique to improve it. I'm naming a ton of variables and repeating code like a madman.

The script is a html dashboard that controls database values to insert into ~160 different website titles/descriptions.

The dashboard code is:

$displayquery1 = "SELECT * from seo where seo_id = 1";
$displayresult1 = mysql_query($displayquery1, $con);

//fetch and print record for page 1

while ($row = mysql_fetch_assoc($displayresult1, MYSQL_NUM)) {

echo '<td align="left"><a href="' . $row[2] . '">' . $row[2] . '</a></td>'
. '<td><input type="text" name="seo1a" value=" ' .  $row[3] . '"></td>'
. '<td><input type="text" name="seo1b" value=" ' .  $row[4] . '"></td>   '
. '<td><input type="textarea" name="seo1c" value=" ' .  $row[5] . '"></td>    
</tr><br>';}            


//fetch and print record for page 2

$displayquery2 = "SELECT * from seo where seo_id = 2";
$displayresult2 = mysql_query($displayquery2, $con);

while ($row2 = mysql_fetch_assoc($displayresult2, MYSQL_NUM)) {

echo '<td align="left"><a href="' . $row2[2] . '">' . $row[2] . '</a></td>'
. '<td><input type="text" name="seo1a" value=" ' .  $row2[3] . '"></td>'
. '<td><input type="text" name="seo1b" value=" ' .  $row2[4] . '"></td>   '
. '<td><input type="textarea" name="seo1c" value=" ' .  $row2[5] . '"></td>    
    </tr><br>';}

and the insert script is:

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
   if (empty($_POST['seo1a'])) {
        echo 'please enter a seo title';
    } else {
        $seo1a = ($_POST['seo1a']);
        $seo1b = ($_POST['seo1b']);
        $seo1c = ($_POST['seo1c']);
        $seo2a = ($_POST['seo2a']);
        $seo2b = ($_POST['seo2b']);
        $seo2c = ($_POST['seo2c']);

        //create queries
    $q5 = "UPDATE seo SET seo_title='$seo1a', seo_description ='$seo1b', seo_content='$seo1c'  WHERE seo_id = 1";
    $q6 = "UPDATE seo SET seo_title='$seo2a', seo_description ='$seo2b', seo_content='$seo2c'  WHERE seo_id = 2";
    $r = mysql_query($q5, $con);
    $r2 = mysqli_query($q6, $con);
    }};

see how I'm naming every single variable and running the queries so repetitively? I have to do this for 160 pages. The way I'm getting the variables from the db is also probably wrong:

//get seo title for first page
$varquery1 = "SELECT * from seo where seo_id = 1";
$varresult1 = mysql_query($varquery1, $con);
if ($varresult1) {
$row1 = mysql_fetch_assoc(mysql_query($varresult1));
$seotitle = row1['seo_title'];
}

//get seo title for second page
$varquery2 = "SELECT * from seo where seo_id = 2";
$varresult2 = mysql_query($varquery2, $con);
if ($varresult2) {
$row2 = mysql_fetch_assoc(mysql_query($varresult2));
$seotitle = row2['seo_title'];
}

Please feel free to excoriate me for the quality of my code just give me a hint or two as well please. Also its not my website so I can't switch to mysqli just yet. Thanks very much

Ruby: How should I access instance variables inside a class?

In ruby you can internally access variables directly via @var_name or via private getters attr_reader :var_name.

Which solution is more (semantically?) correct? Any advantages/disadvantages of using either solution 1 or solution 2?

Solution 1:

class Point
 def initialize(x, y)
   @x = x
   @y = y
 end

 def distance
   Math.sqrt(@x ** 2 + @y ** 2)
 end
end

Solution 2:

class Point
 def initialize(x, y)
   @x = x
   @y = y
 end

 def distance
   Math.sqrt(x ** 2 + y ** 2)
 end
 private attr_reader :x, :y
end

Valgrind through Memory leak if Singleton object is not deleted? [duplicate]

This question already has an answer here:

I just entered into to creational  design pattern in C++, in which I selected to start with Singleton class. I went through many online tutorial and find that what singleton can do for me are:

  1. It will give global access to an object, and
  2. It is guarantee that no more than one object of this type can ever be created

My questions are:

  1. How can I deleted the allocated memory done on heap by new operator because my valgrind through as memory leak?
  2. How to call a destructor of class when object stay in heap?
  3. Can I use stack object instead of heap object?
  4. Any Visual example for singleton class that I can think of with real time example?

Below is my code. Please help me to understand.

#include<iostream>
using namespace std;
class hello
{
        public:
                static hello *OneObj;

                static hello *MakeOneObject(); //funtn with return static class obj
                           private:hello()
                {
                        cout<<"One Object created"<<endl;
                }
                ~hello()
                {

                        cout<<"Object deleted"<<endl;
                }

};

hello* hello::OneObj=NULL;
hello* hello::MakeOneObject()
{
        if(OneObj==NULL){
            cout<<"in if"<<endl;
        //        hello OneObj; why stack object not possible?
            OneObj=new hello();
}
        return OneObj;
}

int main()
{
        hello *h,*jj;
        h=hello::MakeOneObject();// created
        jj=hello::MakeOneObject(); // not created

       }

vendredi 30 octobre 2015

Understanding design patterns and struggling to write code for it

I'm trying to understand design patterns and I want to implement the best way into my project. I have been reading about it last two days and I understand that singleton pattern is not good unless you want to use it for database. And I wrote the bellow code which is I believe factory pattern. But I don't understand why do I need to use interface? Is there anything wrong with my code? Could you give me any example? My goal is that I want send mail without writing settings for phpmailer every time I need to send mail. Or for any other library I use.

Thanks.

this is my folder structure..

-lib
---Config.php (configuration class)
---Mail.php
-logs
-models
---Users.php
-public (web root)
---index.php (get routers)
-routers
---users.router.php
-templates
---users.html.twig
-vendor
---slim
---phpmailer
.composer.json
config.php

Mail.php

class Mail {
    protected $mail;

    public function __construct(PHPMailer $mail) {
        $this->mail = $mail;
        $this->mail->isHTML(Config::read('mail.isHtml'));
        $this->mail->setFrom(Config::read('mail.fromEmail'), Config::read('mail.fromName'));
    }

    public function sendMail ( $to, $subject, $body, $plainText ) {
        $this->mail->addAddress($to);
        $this->mail->Subject = $subject;
        $this->mail->Body = $body;
        $this->mail->AltBody = $plainText;

        $this->mail->send();
    }
}

user.router.php

$app->get( '/test', function () use ( $app ) {

    $app->log->info("test '/test' route");

    $mail = new PHPMailer();
    $test = new lib\Mail($mail);

    $test->sendMail('test@domain.com', 'Subject', '<html>Hello username</html>', 'Hello username' );


    var_dump($test);
});

config.php

Config::write('mail.fromEmail', 'no_reply@domain.dev');
Config::write('mail.fromName', 'Domain LTD');
Config::write('mail.isHtml', true);

name of the pattern or technique

I am new to c# programming and I apologize for my beginner level question. I have tried to google about this pattern but have been unsuccessful. While learning about c# MVC/WCF on the net, I have come across various examples where it uses the following pattern or technique:

       public PaperResponse GetPaperResults(LearnerPaperRequest request)
    {
        return LearnerResponse.GetPaperResults(request);
    }

where

    public static class LearnerResponse
    {
        public static PaperResponse GetPaperResults(LearnerPaperRequest request)
        {
             //do work by calling Business logic layer or do work here itself like calling service or db
              return paperResponse;
        }
    }

I am trying to find the name of this pattern or technique so that I can read more about this pattern or technique.

How to limit class object in C++ [duplicate]

This question already has an answer here:

I want limit object that can construct (2 more object) Singleton Pattern is similar this solution but only useful to only one object.

I need your help. HELP..

How to call function from a member class?

How to call function(AddUnit) from a member class(menu)? Or how to organise this code?:

class Base
{
    BaseMenu *menu;
    virtual void AddUnit(Unit* unit);
}

I writing something like stategy or tactic game. Menu has buttons and I want to add units by clicking on this buttons. How to organise this or How to make different menu for different bases? Maybe out menu from base class ?

Tree structure late initialization

i'm looking for an elegant solution for my problem.

The situation:

I have some files, that must be imported in a data management system (dms), which stores the files in a folder structure. Because the folders in this dms are not just plain folders, but can have different characteristics, i have a different class per folder type. They all implement my interface IFolderEntity. A IFolderEntity has its own folder name and its parent IFolderEntity.

My problem is:

While processing the files, i do not know the folder structure in advance. The folder path must be determined for each file on a set of custom rules. To get the IFolderEntity for a path, i have build a FolderEntityFactory which returns the IFolderEntity with a set parent for a given path.

But it is possible that a path is requested, where the type of parent folders is not yet specified. Maybe the parent directories will be specified by later files and rules, maybe they will not be specified at all and will just be created as default folders.

It is possible, that values will be set or retrieved or an event will be subscribed, before the final request of the parent IFolderEntity, where a new object could be created.

The files and directories will be imported and created after this processing step. So it just resides as information in the memory till the point, the processing is finished.

Example:

File1 requests folder path /root/directory/subdirectory/filedirectory/
The FolderEntityFactory searches for the parent IFolderEntity with the path /root/directory/subdirectory/. Because this parent path was not requested explicitly previously and so there is until now no IFolderEntity for this parent path. Because of this, a new default IFolderEntity (DefaultFolderEntity) will be built.

Later in the processing of the files, the parent path /root/directory/subdirectory/ will be requested as special type. So instead of a DefaultFolderEntity another class type (CharacteristicsAFolderEntity) have to be built.

In this case, the previous parent folder entity is obsolete and could be replaced.

My current solution

Currently i am using a kind of proxy class, that will buffer all requests until a concrete object would be created. at this point, the proxy just delegates all requests to the concrete object.

The question

I don't think that this is a good solution and that i am barking up the wrong tree. So i am looking out for some recommendations, what a good solution to this problem could look like. Because of the simple fact, that i don't really know what i am searching for, i also couldn't find a solution by myself. If someone could point me in the right direction, that could be enough.

Many thanks in advance for your suggestions

ASP.NET MVC - Proper usage of View Model and Command pattern

I've been writing ASP.NET MVC applications for some time and I found them to be a good place for using the command pattern: we represent every user request as a command - a set of input params - then this command is processed (processing includes validation and other domain logic) and the result is sent back to the user.

Another thing I've been using in my applications is view models. I found them to be a more convenient way of passing data to the view than using domain objects as models or filling ViewData/ViewBag.

These 2 concepts work great for separating data that is shown to the user from user input and its handling, but they don't quite agree with each other in ASP.NET MVC.

Let's say I want to use commands and view models when developing a simple web store where users look through products and can order a product by providing their name and email address:

class ProductViewModel 
{
    public ProductViewModel(int id) { /* init */ }
    public int Id { get; set; }
    public string Name { get; set; }
    // a LOT of other properties (let's say 50)
}

class OrderProductCommand
{
    public int ProductId { get; set; }

    [Required(ErrorMessage = "Name not specified")]
    public string Name { get; set; }

    [Required(ErrorMessage ="E-Mail not specified")]
    public string Email { get; set; }

    public CommandResult Process() { /* validate, save to DB, send email, etc. */ }
}

When looking through tutorials and SO I've seen people suggest several ways of doing this.

Option 1

Controller:

[HttpGet]
public ActionResult Product(int id)
{
    return View(new ProductViewModel(id));
}

[HttpPost]
public ActionResult Product(OrderProductCommand command)
{
    if (ModelState.IsValid)
    {
        var result = command.Process();
        if(result.Success)
            return View("ThankYou");
        else
            result.CopyErrorsToModelState(ModelState);
    }
    return Product(command.Id);
}

View:

@using (Html.BeginForm())
{
    @Html.Hidden("ProductId", Model.Id)
    @Html.TextBox("Name")
    @Html.TextBox("Email")
    <input type="submit" value="Place order" />
}

Pros: view model and command are separated from each other, the HttpPost method looks clean

Cons: I can't use convenient HTML helpers like @Html.TextBoxFor(model => model.Email), I can't use client validation (see my other question)

Option 2

We copy Id, Name and Email together with their validation attributes from command to viewModel.

Controller:

[HttpPost]    
public ActionResult Product(ProductViewModel viewModel)
{
        var command = new OrderProductCommand();
        command.Id = viewModel.Id;
        command.Name = viewModel.Name;
        command.Email = viewModel.Email;        
        if (ModelState.IsValid)
        // ...
}

View:

@Html.TextBoxFor(m => m.Email)
...

Pros: all of option 1 cons go away

Cons: copying of properties seems inconvenient (what if I have 50 of them?), validation of Name and Email in view model (it should be done in command where the rest of the domain logic resides), model as a POST parameter (see below)

Option 3

We make command a property of viewModel.

Controller:

[HttpPost]
public ActionResult Product(ProductViewModel viewModel)
{
        var command = viewModel.Command;
        if (ModelState.IsValid)
        // ...
}

View:

@Html.TextBoxFor(m => m.Command.Email)
...

Pros: all of option 1 cons go away

Cons: view model should only contain data that is displayed to the user (and command is not displayed), model as POST parameter (see below)

--

What I don't like about options 2 and 3 is that we use a view model as a POST method parameter. This method is meant for handling user input (only 2 fields + 1 hidden in this case) and the model contains 50 more properties that I'll never use in this method and that will always be empty. Not to mention the necessity to create an empty constructor for the view model just to handle this POST request and the unnecessary memory consumption when creating large view model objects for every POST request.

My question is (that's like the longest question ever, I know): is there a secret Option 4 for properly using commands and view models that has all of the pros and none of the cons of the other ones? Or am I being paranoid and these cons are not that important and can be ignored?

jeudi 29 octobre 2015

why table and tablebuilder in leveldb use struct rep?

Recently I read the source code of leveldb, but I am confuse about the rep struct in the table and table_builder source.

since we can directly store the member variable directly in the class Table and class TableBuilder.

But why the author make a struct Rep, and store the member variable in the struct Rep.

I can come up whit one reason, because the table and table_builder will expose to the user, so we want to hidden the implementation. Is it right? or there is some other idea that I miss, or is it some design pattern?

Thank you

Composing Interfaces in C++

Suppose I wish to write a C++ function that takes as its argument an object that conforms to two unrelated interfaces. There are several ways this might be done; I list three below along with my critiques. (Please bear with me until I get to the actual question).

1) As a template function

template<typename T> void foo(const T& x) {
    x.fromInterfaceA();
    x.fromInterfaceB();
}

This is perhaps the best of the 'standard' solutions, but ensuring that x really inherits from A and B requires additional static_asserts, type_traits, etc., which is clumsy and long-winded. Also, the user is forced to constantly write template code where in fact there is no really generic behavior desired.

2) By having the function accept a specific derived class

struct A {
    // ...
    virtual void fromInterfaceA() = 0;
};

struct B {
    // ...
    virtual void fromInterfaceB() = 0;
};

struct AB : public A, public B {};

void foo(const AB& ab) {}

We are forced to create a new class just to express the composition of two other classes, and, even worse, foo() is not able to accept arguments that might inherit from A and B via a different route, e.g. through an intermediate class. We could quickly have a taxonomic nightmare, where there are multiple micro-interfaces.

3) By having foo accept a separate argument for each type, and passing the object multiple times.

void foo(const A& xAsA, const B& xAsB) {}
int main() {AB ab; foo(ab, ab);}

This is the most flexible solution (since it would also fit well with a composition-over-inheritance approach), yet it is also confusing, obscures the fact that foo is supposed to operate on a single object, and allows foo to accept two separate objects, possibly leading to pathological behavior.

In Haskell, we can compose type constraints in the way I'm talking about. It would be nice if syntax existed in C++ that allowed the same thing; I can see, though, that this would have serious implications for the internals of the class mechanism. We could write a template class, something like this rough sketch:

template<typename T1, typename T2> class Composition
{
    public:

        template<typename T> Composition(T& t) : t1_(t), t2_(t) {}

        operator T1&() {return t1_;}
        operator T2&() {return t2_;}
        template<typename T> T& as() {return operator T&();}

    private:

        T1& t1_;
        T2& t2_;
};

which appears to offer the advantages of the template solution, (1), while quarantining the actual template code.

My question is: are there any standard design patterns that deal with this issue? Or, alternatively, is there a paradigm where the problem goes away, while still allowing the same kind of flexibility I'm talking about? I'm also interested in more general critiques or thoughts on the discussion above.

Recommendation for online store system design? (course project) - deep

This coming semester I'm doing a project in Andorid&Java in which we need to create an app for a book store, which has also a web site, and can have different sellers (others than the owner) to sell in that store. Kind'a like ebay and amazon, but only with books.

I'm trying now to decide how to design this system. I have an idea, but seance this is my first time, I thought it would be smart to ask in the Stack Overflow community, 'cus people here have a lot of experience. Si where can I learn how to manage such system? again - I'm tying to do this similar to ebay/amazon systems (like enabling search for books, and getting different books from different sellers)

This is how I think to design it, and pls tell what you think: pros/ cons There are going to be some main enteritis (in run time) like Seller,Book,User,Store , and all have basic info about them like address, phone number, email, author etc. Note: Seller class does NOT hold the store class, store doesn't hold book classes - no entity is connected to an another .

In my server, there is going to be a Data base for each entity, and there will be relational table, holding relations like store-seller, book-seller, user-bought_from - store.

When a User wants to buy from a store, he's (the app) is going to send a query to my server, with information about what store does he wants to buy from (lets say for now he knows what store) and the server is going to look inside in his book-store relational table, and will return all the books (or some 'part' of them, no need to get all the info on first fetch) of that store.

All that info will come back to the app/website, will be 'combined' with the store that has that book and the book (so when a user wants to buy from multiple stores - when he pick a book, each objects he selects, could be connected to the store that has it.) and will be displayed there.

This is very general, but the main point is the entities don't contain other entities, but instead all entities that are being used at runtime (like store, book, user, seller, etc.) are more like info cards to know what info to get from the data base.

This way I think some thing could be some what more simple, and the app CMS could be similar to the server CMS.

But I'm not quiet sure, maybe I should just do it a more direct approach, like that a seller will contain a store that will contain books.

The problem with that design is that I think that maybe it makes it harder for specif info query (unless a when you fetch info a seller will not contain all info on books?)

And if I have other objects, like and order-book object. Where that object will be contained? because user and seller both need access to it. and what if not all data is loaded at runtime, but only part of is, and instead all the rest will be disciplined as ID of the other objects that are not loaded, so the app will to get the extra info when it wants it.

I'm really debating on what to do, so I would like to get some advice, and leads to where to learn how manage/design such system.

Thanks!

Which design pattern should I use to design user authentication system? [on hold]

I am creating an application in which, the user first has to login. The user can be from any device, PC, laptop, Mobile phones, PDA, any. I want to design a system which uses REST based authentication. Please, tell me what kind of pattern for the purpose. I am using JAX-RS for the system.

How to design a class which reads properties from a file

I want to know what is the best programming practice in Java to design a class which reads the properties from a config/ini file. Since properties cannot change during the execution of the program, Is it advisable to make the class as a Singleton class? One of the function to be constructed is read() method which reads configurations from a config file and sets the configurations. Also should i make getters and setters for all the properties derived from the config file.

Error "cannot be resolved to a type" using the Factory Methond

I'm trying to use the design pattern "Factory Method" on DAO. There are some problems with the type resolving when I call the method to create the correct instance. This is the main where I call the method and I get the error:

public class Main {

public static void main(String[] args){
    int scelta=1;

    Parametri<InterfacciaTO> p=new Parametri<InterfacciaTO>();
    //here I get the error
    DaoInterface dao=(DaoInterface) new MySqlDAO.getInstance(scelta,p);


}

}

These are the classes that I use to implement the FactoryMethod.

public interface DaoFactory {

    public abstract Object getInstance(int code,Parametri<InterfacciaTO> param);

}

public  class MySqlDAO implements DaoFactory {

@Override
public DaoInterface getInstance(int code, Parametri<InterfacciaTO> param) {
    switch(code){
    case Indici.UTENTEDAO: return new UtenteDAO();
    }
    return null;
}   
}

public interface DaoInterface {

public abstract void create(int code,Parametri<InterfacciaTO> param);

public abstract void delete(int code,Parametri<InterfacciaTO> param);

public abstract void update(int code,Parametri<InterfacciaTO> param);

public abstract void search(int code,Parametri<InterfacciaTO> param);

}

public class UtenteDAO implements DaoInterface {

@Override
public void create(int code, Parametri<InterfacciaTO> param) {
    System.out.println("CIAU");

}

@Override
public void delete(int code, Parametri<InterfacciaTO> param) {
    // TODO Auto-generated method stub

}

@Override
public void update(int code, Parametri<InterfacciaTO> param) {
    // TODO Auto-generated method stub

}

@Override
public void search(int code, Parametri<InterfacciaTO> param) {
    // TODO Auto-generated method stub

}

}

What is a good design pattern for generic utility functions that don't fit in any class

I am working on a project in Python using the Object Oriented paradigm.

I have two utility functions that do not semantically fit in my class since they are generic and can be re-used across different classes and indeed, different projects. I'd like them separate to ensure maximum reusability (following the Don't Repeat Yourself (DRY) Principle).

One function takes a sequence of dictionaries and merges them using a dict comprehension:

def mergedict(dictionaries):
    return  {
                k:v
                for d in (dictionaries)
                    for k, v in d.iteritems()
            }

Another takes a string and returns its integer value or 0 if it isn't numeric.

def getint(s):
    try:
        i = int(float(s))
    except ValueError:
        i = 0

    return i

For these types of functions, should I:

  1. Define a utility class with static methods (which seems like a misuse of the OOP paradigm)
  2. Define them as functions in a module (maybe have a module for each type e.g. string_utils, dict_utils etc)
  3. A better way?

I'm struggling to determine the best semantic placement for such functions. getint() could be a method of a class that is a wrapper of Python strings but mergedict() seems more vague.

How have others handled this type of issue, possibly in a manner that retains OOP purity?

How to design factory pattern for different types of values in one list?

I need to design a data structure that holds different types of values (doubles, strings, datetimes, etc.). The list of types is dynamically created by user. Based on that list another list of values should be created. Then this "record" of values is to be sent by WCF and stored in dynamically created db table. I'm starting with desiging this solution in c#. My current status is shown below. I'm not satisfied with my present solution, especially with factory and enums. Is there better way to do the things right?

Enum for my types:

public enum ValueType { Decimal, String, Boolean };

then interface:

public interface IValueType
    {
        object Data { get; }
        string ToString();
        ValueType? Type { get; }
    }

base class:

public abstract class ValueType<T> : IValueType
{
    protected T _Value;

    public ValueType(T value)
    {
        _Value = value;
    }

    public object Data
    {
        get { return _Value; }
    }

    public ValueType? Type
    {
        get { return null; }
    }
    public T Value { get; private set; }
    public override string ToString()
    {
        return _Value.ToString();
    }
}

one of implementation:

public class DecimalValueType : ValueType<decimal>
{
    public DecimalValueType( decimal val ) : base(val)
    {}
    public DecimalValueType(double val) : base((decimal)val)
    {}
    public DecimalValueType(int val) : base((decimal)val)
    {}
}

then factory:

public static class ValueTypeFactory
{
    private static Dictionary<ValueType, Type> dictValueType = new Dictionary<ValueType, Type>()
    {
        { ValueType.Decimal, typeof(DecimalValueType) },
        { ValueType.String, typeof(StringValueType) },
        { ValueType.Boolean, typeof(BooleansValueType) }
    };

    private static Dictionary<Type, Type> dictSimple = new Dictionary<Type, Type>()
    {
        { typeof(decimal), typeof(DecimalValueType) },
        { typeof(double), typeof(DecimalValueType) },
        { typeof(int), typeof(DecimalValueType) },
        { typeof(string), typeof(StringValueType) },
        { typeof(bool), typeof(BooleansValueType) }
    };

    public static IValueType MakeByValueType(ValueType type, params object[] initValues)
    {
        IValueType retObject = null;
        if (dictValueType.ContainsKey(type) )
        {
            Type t = dictValueType[type];
            retObject = (IValueType)Activator.CreateInstance(t,initValues);
        }
        return retObject;
    }

    public static IValueType MakeByType(params object[] initValues)
    {
        IValueType retObject = null;
        if ( initValues.Length > 0 )
        {
            Type type = initValues[0].GetType();
            if (dictSimple.ContainsKey(type))
            {
                Type t = dictSimple[type];
                retObject = (IValueType)Activator.CreateInstance(t, initValues);

            }
        }
        return retObject;
    }
}

sample use:

    List<IValueType> lista = new List<IValueType>();
    lista.Add(new DecimalValueType(12));
    lista.Add(new StringValueType("Test"));
    lista.Add(new BooleansValueType(true));
    lista.Add(ValueTypeFactory.MakeByValueType(ValueType.Decimal, 10.1));
    lista.Add(ValueTypeFactory.MakeByType(5.12));
    lista.Add(ValueTypeFactory.MakeByType("Test2"));

I would be happy with any advice.

Looking for standard cordova/ionic app design pattern

I'm developing an app in Ionic and see that the seed app structure is too simple.

So, is there any standard design pattern for cordova or ionic app?

Java Binary Trees/Visitor Pattern

So I can really get this I was wondering if anyone could help me out, the object of this program is to use the visitor pattern to generate a list of strings from the name of people in a given binary tree, if not really sure how to go about using an append function to do so. How would I append the person with its parents?

import tester.Tester;

//Representation for an ancestor tree
interface IAT {
    <R> R accept(IATVisitor<R> visitor);

    //Append two lists
    IList<String> append(IList<String> l);
}
//-------------------------------------------------------------------------------------------------
//Unknown person
class Unknown implements IAT {
    Unknown() {
    }
    public <R> R accept(IATVisitor<R> visitor) {
        return visitor.visitUnknown(this);
    }
    //append two an unknown
    public IList<String> append(IList<String> l) {
        return l;
    }

}    
//-------------------------------------------------------------------------------------------------
//Representation for a person
class Person implements IAT {
    String name;
    int yob;
    boolean isMale;
    IAT mom;
    IAT dad;
    //Constructor
    Person(String name, int yob, boolean isMale, IAT mom, IAT dad) {
        this.name = name;
        this.yob = yob;
        this.isMale = isMale;
        this.mom = mom;
        this.dad = dad;
    }
    public <R> R accept(IATVisitor<R> visitor) {
        return visitor.visitPerson(this);
    }
    //append parent and children of tree
    public IList<String> append(IList<String> l) {
        //
    }

}
//-------------------------------------------------------------------------------------------------
interface IATVisitor<R> {
    R visitUnknown(Unknown u);
    R visitPerson(Person p);
}
//-------------------------------------------------------------------------------------------------
//IAT Visitor that returns a list of the names of all people
class IATVisitGetNames implements IATVisitor<IList<String>> {
    public IList<String> visitUnknown(Unknown u) {
        return new MT<String>();
    }
    public IList<String> visitPerson(Person p) {
        return new Cons<String>(p.name, new MT<String>());
    }
}

//Examples
class ExamplesIATV {
    //persons
    Unknown a = new Unknown();
    Person ralph = new Person("Ralph", 1995, true, a, a);
    Person kevin = new Person("Kevin", 1994, true, a , a);
    Person julia = new Person("Julia", 1991, false, ralph, a);
    Person lily = new Person("Lily", 1990, false, kevin, julia);
    Person who = new Person("?", 1738, false, lily, a);

    //Visitor
    IATVisitor<IList<String>> byName = new IATVisitGetNames(); 


    //test Vistior
    boolean testGetNames(Tester t) {
        return 
                t.checkExpect(who.accept(byName), new MT<String>());
    }
}

mercredi 28 octobre 2015

java job detail confusion

I have some doubt. I got an email and in the email they said : Possess expertise in Design Patterns, Low level designing. What does this low level designing mean? Is that related to UML ?
Please let me know.

Thanks in advance.
JB

Design of the engine in C++

I have to design a class with include many engine calculation (5 at max) for an object A. How to design properly, so new engines can be added.

Class Base: Calculate which uses one of the Engine.

Engine: get xdata and gives double ydata. method: initialize, calibration, calculate,...

Can I do a a switch (simpler, not heavy) in Calculate ?

switch (engineID)
1: Use Engine1
2: Use Engine2
....

I dont want to create a derived class for each engine, since this is mainly C code calculation (numerical algo).

I think this is very common issue in design: making simple or adding new classes....

How to use external libraries in a project?

I use slim framework for a project and I use singleton design pattern for PDO database connection. I install libraries with composer and I have a autoloader.

here is my static PDO connection class.

<?php
namespace lib;
use lib\Config;
use PDO;

class Core {
    public $dbh; // handle of the db connexion
    public $mail;
    private static $instance;
    private function __construct() {
        // building data source name from config
        $dsn = 'mysql:host=' . Config::read('db.host') .
               ';dbname='    . Config::read('db.basename') .
               ';port='      . Config::read('db.port') .
               ';connect_timeout=15';
        // getting DB user from config                
        $user = Config::read('db.user');
        // getting DB password from config                
        $password = Config::read('db.password');
        $this->dbh = new PDO($dsn, $user, $password);
    }
    public static function getInstance() {
        if (!isset(self::$instance))
        {
            $object = __CLASS__;
            self::$instance = new $object;
        }
        return self::$instance;
    }
}

And I have a separate config.php file which holds the configs(dbname, db username, db password) and I use $db = \lib\Core::getInstance(); where ever I want if I need.

Now, for example if I want to use PHPMailler library it has some options. When I need to use phpmailler in a route or a class I have to set all the settings first. then send the mail. Is it okay to use singleton design pattern like above and set everything like sender e-mail, smtp credentials etc..., hold settings in the config.php and then call only send object where ever I want. Is singleton design pattern good for this? I would like to have my config.php file which should hold all the options for any library I install and use these libraries in a class, function, route etc.. without having to set everything every time I use a library.

Is factory design pattern for this purpose or singleton design patter okay?

Thank you.

General purpose cache with replaceable algorithm

I am aiming to implement a cache in java, such that the user of the cache to determine which algorithm to use for this cache. This can be a general purpose cache and user can decide to use it as LRU or MRU or some other strategy.

which would be a good design pattern for this? Goal is to encapsulate all my internal data structures that I use for cache at the same time exposing right interfaces so user of the cache can plug-in their own caching algorithm ( LRU, MRU, etc.)

I am inclined towards using dependency injection, and injecting a "delegate" to the constructor of the cache, such that this delegate would govern which caching strategy is implemented.

Just wanted to check if there are any thoughts/suggestions on this design so that I can have a clean separation betweeen (a) the cache implementaion ( and internal datastrctures) and (b) actual caching strategy.

Thanks a bunch in advance.

Extract locations of a string and associate information with this parts

I have a string that inside has some kind of metadata that "describe" parts of the string.
Example:

This is an {TypeAStart}arbitrary long{TypeAEnd} text which has {TypeBStart}various{TypeBEnd} usages  

What I want is to get the indexes of the strings that are contained inside these tags.
My first thought was something like:

String[] tags = [ "{TypeA", "{TypeB", etc ];  
for(String tag:tags)  {  
   int start = mainString.indexOf(tag + "Start");  
   if(start != -1) {  
      int end = mainString.indexOf(tag + "End}", start);  
      // store somewhere start,end  
   } 
}   

But I think this approach is hacky and error prone. How can I do this efficiently with regexes?

UPDATE:
I have this string as I mentioned and these metadata are marks where styling is to be applied. So my main problem is to find an effective way to extract the positions of the string that the styling is to be applied (marked by these custom tags) and be able to figure out for each tag (which maps to a style) which indexes/pars of the string are affected. My main target is to have the original string stripped of the tags and in another data structure the indexes and styles.

Two seemingly identical sed commands, one works, the other doesn't. Can you tell me why?

There's something I'm having trouble understanding concerning sed behavior.

sed -n "/pattern/,$p" < input.inp > output.out

gives the following error

sed: -e expression n°1, caractère 10: `,' inattendue

(my system is in french).

sed -n '/pattern/,$p' < input.inp > output.out

Works fine

I've personnally used commands like

sed -n "/begin/,/end/p" < input.inp > output.out

with both single or double quotes, and they work just fine.

In case it's useful, I have sed version: sed (GNU sed) 4.2.2

Is passing class in java as argument good choice for getting information about concrete implementation of interface?

i have problem with interface's method. It's rather design problem than programming implementation problem.

I tried to implement Composite Design Pattern in my project. Firstly, I was using Enum to distinguish different kind of elements (getElementType was main method to ensure what information is inside the object - there were a lot of different Tree elements). This solution was terrible... I know

I deleted enum and created many smaller classes, used inheritance and implemented concrete method from my interface for each Object.

TreeElem elem; // ... etc

if(elem.getElementType()==ElemType.LEAF){
    elem.action();
}

public interface Actionable{
    void action();
}

public class ElemLeaf extends TreeElem implements Actionable{

    public void action(){
        // something funny haha
    }
}

Actionable elem = new ElemLeaf(); 

elem.action();

But sometimes I want to know, which class this object is, so I created method and added to Actionable interface

public Actionable doSomething(Class classOfElement){

    if(classOfElement.equals(ElemLeaf.class){

        return this;

    }
    else{

        return new ElemLeaf();

    }
}

I don't know if it is a good design principle to put Class as parameter or it is terrible choice. Maybe I should change my classes and interfaces composition to avoid this situation.

I hope that I made myself clear. These examples are not from my project, but they are similiar.

How to get information about a JavaEE project?

I want to make a JAVA-EE project, actually a web base application but i don't know how to start it. If I want to get specific about it at the first place I don't know which project is the best one to test my skills in java, for example creating a web application for shopping like Amazon or another one to communicate like Facebook or Instagram. After choosing my topic to create a web application I don't know which structure is the best one to program (like which packages and classes I need). I don't have any experience working in companies, so in need to do this project to show my skills. If you show me some websites or books which can get me to my point as fast as possible I'll be really thankful.

How to subclass a parent for mocking

How do I subclass a parent class with a private constructor so that I can mock it?

I have refactored my code such that when it makes a call to a third party library, the calls are wrapped so that I can mock the class and create a fake wrapper. I can then in theory return whatever I want to test my production code using dependency injection etc.

For a few of the library calls, a single object instance is returned which in itself is a specific library object type. In the production code, this then has subsequent calls made upon that object.

This is illustrated in the code below:

public class MyWrapper
{
  public LibraryObject getX()
  {
    LibraryObject x = ExternalLibrary.getX();
    return x;
  }
}

public class MyProductionCode
{
  public void DoX()
  {
    LibraryObject lo = MyWrapper.getX();
    ProductionType pt = lo.doSomething();
  }
}

How do I fake the method doSomething() ? My first thought was instead of returning an instance object from the wrapped call, return an object which is of the same type. So MyWrapper code could be enhanced as follows:

public class MyWrapper
{
  public LibraryObject MyWrappedCall()
  {
    //LibraryObject x = ExternalLibrary.getLibObject();
    MyMockLibraryObject mlo;
    return mlo;
  }

  public class MyMockLibraryObject extends LibraryObject
  {
    public ProductionType doSomething()
    {
      ProductionType pt;
      return pt;
    }
  }
}

The problem with this is that the parent class has a private constructor, so it cannot be subclassed.

Does anybody have any suggestions of how to get around this?

Using strategy to create subclasses from superclasses

I have a C#/OO/Design related question.

I am redesigning an old system that was ported to C#. We are refactoring the system to make it more simple and more object oriented.

In this system we have various objects related to our business domain - Folder, Document, User, Appointment, Task, etc. All of these objects inherit from a base object called, believe it or not, BaseObject:

public class BaseObject {
    public int Id { get; set; }
    public string Name { get; set; }
}

This object is not abstract because we actually instantiate it for some simple lists.

We also have our own Generic list:

public class CustomList<T> : IENumerable<T> where T : BaseObject {
    //... several properties and methods

    }
}

My questions is this: I have many objects that inherit from BaseObject. For example, I can create a CustomList<User> because User : BaseObject.

However, many of my user controls return CustomList<BaseObject>, simply because that is what most list-based user controls CAN return: they know each object's name because that's what they display, and they use its Id as a key.

So, I would like to be able to add the items from a CustomList<BaseObject> to any CustomList<T>. I want to be able to add objects, not just construct a new list.

But because I can't just cast from a superclass (BaseObject) to a subclass (e.g. User), I was thinking about implemeting the following method inside CustomList<T>:

public void AddRangeOfBaseObjects(IEnumerable<BaseObject> items, Func<BaseObject, T> constructor)
    {
        foreach (var item in items)
        {
            var newObject = constructor(item);
            Add(newObject);
        }
    }

Or in other words, if a class needs to create a CustomList from CustomList, it needs to supply both the CustomList and a method saying how to construct each new instance of T from BaseObject, and how to initialize its other members which BaseObject doesn't know.

I believe this is similar to a Strategy pattern. Of course the method itself hardly has any code, but due to the ubiquity of this action, it is still shorter to design it like this.

The question is - is this good design? Is there a better pattern for handling this situation of moving simplified version of objects from the UI into actual objects?

How to ensure only the owner of pawns in a game is able to move them?

The pawns can be traded between the owners. So at different times, a pawn may have different owner.

Say, pawn has function moveTo(i,j)

How to enforce the above mentioned constraint?

How can I design using Java - OOP concepts? [on hold]

How can I design using Java - OOP concepts?

Design a building like a cotagge and provide a builder to build it.

Design a school and provide classes to build it (builder, factories, etc).

Sending Array List using Dagger 2

i'm new to dependency injection and Dagger 2 library for android mainly my question is in 2 parts the first is it a good practice to use dagger 2 to set a list for my custom adapter say i have like this

    package com.example.a3adel.vogellaexample;

import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

import java.util.ArrayList;

import javax.inject.Inject;


public class ListAdapter extends BaseAdapter{
    LayoutInflater inflater;
    @Inject
    ArrayList<String> listArray;
    public ListAdapter(Activity context){
        MyApplication app = (MyApplication) context.getApplication();

        app.getComponent().inject(this);

        inflater=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }
    @Override
    public int getCount() {
        return listArray.size();
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View view=inflater.inflate(R.layout.listitem,parent,false);

        return view;
    }
}

and i initialize the arraylist in the main activity like this

 @Provides
    @Singleton
    ArrayList<String> getList() {
        ArrayList<String> list = new ArrayList<>();
        list.add("test");
        list.add("test2");
        list.add("test3");
        return list;
    }

i have my component like this

@Singleton
@Component(modules = {MainActivity.class})
public interface DiComponent {
    void inject(ListAdapter adapter);

}

and if it's a good practice is this the best way to be done ?? thanks

How to avoid lots of if-else in javascript (nodejs) [on hold]

Based on a parameter, function should select a json file out of more 100 json and fire a query to other system.

There will lots of query around in hundreds.

Obviously if else and switch won't be manageable. I took a look for strategy patten in the javascript.

Thanks in advance for any suggestion for this problem.

Secondary Use case scenario

I know how to write primary use case scenarios for documenting the use case diagrams. But i couldn't find a way to include secondary scenarios. Is there a format, or way to include it? I googled everywhere but there's no mention about secondary use case scenarios. any help would be appreciated. I just want a format or example.

Thank you.

mardi 27 octobre 2015

Why singletons static method getNext() returns incremented value

I have a singleton class with a static method getNext()

public class Sequence {

   private static Sequence  instance;
   private static int counter;

   private Sequence () { // note: private constructor
      counter = 0;
   }

   public static Sequence getInstance(){
      if(instance==null) { // Lazy instantiation
         instance = new Sequence(); 
      }
      return instance;
   }

   public static int getNext(){ return ++counter;}
}

In my test code I have a for loop which calls getNext() several times

public class TestSequence {
   public static void main(String[] args) {
      for (int i = 0; i < 5; i++)
         System.out.println(Sequence.getNext());        
   }

}

and output of it is

1
2
3
4
5

Why is that? With my understanding of static I thought that output always will be 1.

I understand use of static method that there is no need to create instance of the class (object). When object is not created, then every call to static getNext() method should increment new (virtual) instance variable counter = 0 and return it.

But my program behave exactly the same way as for non static method. Why? Probably I misunderstand something or simplify things.

Can I create singleton child class?

I have parent class:

class ParentClass {
public:
    ~ParentClass(){}
    static ParentClass &getInstance() {
        static ParentClass instance;
        return instance;
    }

    void methodA() {
        //do some stuff
    }

    void methodB() {
        //do some stuff
        methodA();
        //do some stuff
    }

private:
    ParentClass(){}
}

I want to create child class:

class ChildClass : public ParentClass {
public:
    ChildClass(){}
    ~ChildClass(){}

    methodA() {
        //do some stuff
    }
}

This code have some obvious problems. First of all I can't create ChildClass in this way (parent's constructor is private). And seems ChildClass can't directly inherited from ParentClass. This classes very similar. And I do not want create two similar copy of this classes.

Probably I can create one base class for ParentClass and ChildClass. I'm not sure but does some method exist for creating childs from singleton?

Looping for printing a Hollow Triangle Pattern

I need help to print a hollow triangle using for loops.

Here is what I have so far:

def typeTriangle(sizeofpattern): #using a simple counter 
firststar = 1
for i in range(sizeofpattern):
    print("*" * firststar)
    firststar+= 1

This prints:

Your Triangle Pattern: 
*
**
***
****
*****

Thanks and i appreciate your help!

Accessing class members from private function

Suppose I have a class, with some methods that I need to access from private functions within that class. Like so:

var A = function( )
{
    this.a = 0;

    var f = function( ){   // Private function
        this.a;   // Undefined
    };

    f( );
};

What would be the better way to do this? I tried to pass this to the function, but it's not practical if I must do it for many functions.

var A = function( )
{
    this.a = 0;

    var f = function( self ){
        self.a;
    };

    f( this );
};

Is there a better way to do this? Or is the design fundamentally flawed and I should consider other alternatives? Thanks!

Command Pattern basics

Suppose I have a file with contents like this, which is a combination of some config information and some commands:

server1 192.168.0.1  
server2 192.168.0.12  
file1 /home/user1/file1  
upload file1 to server1  
ping server1  
replicate server1
shutdown server1  

The command pattern is well-suited to this as each of "upload", "ping", "replicate", and "shutdown" can be represented as a command.

However, I still have a few questions:

1. Whose responsibility is it to parse the input?
The input file has necessary information like where the files and servers are. Who will do the parsing? Client? Receiver? Invoker?

2. Where should the parsed information be stored?
The parsed information from first 3 lines would go in a HashMap. According to DZone's blog post,

The Receiver has the knowledge of what to do to carry out the request.

So, I am guessing Receiver is the one where the HashMap will stored?

3. Can commands return results?
Commands like "ping" or "shutdown" should indicate what happened after the command was executed. Can these commands return values?

If we are using Factory Pattern should we hide products from user?

Let say I have an AnimalFactory class which produces Dog, Cat and Fish. Using the AnimalFactory makes things incredibly simpler and everything is fine.

My question is that Is there a rule or good practice that suggests us hide Dog, Cat and Animal from being used directly? I mean Dog myDog = new Dog(); will be forbidden in the code.

If there is, how can we hide them properly?

Abstract method to be overridden with concrete type

Maybe this is a dumb question. But, I don't get the point what I am missing.

Given the following class-definition

public abstract class AbstractBaseClass
{
    public abstract void Create(AnotherAbstractClass param1);
}

Wheras AnotherAbstractClass is defined

public abstract class AnotherAbstractClass
{
}

with a concrete implementation

public class AnotherConcreteImplementation : AnotherAbstractClass
{
}

I want to be able to have the override of the Create method to use a concrete type:

public class ConcreteImplementation : AbstractBaseClass
{
    public override void Create(AnotherConcreteImplementation param1) <-- There is no suitable method for override
    {
        // param1 is an instance of the concrete implementation
    }

    public override void Create(AnotherAbstractClass param1) <-- this is working but I'll have to cast on each implementation
    {
        // param1 is an instance of the abstract class and needs a cast
    }
}

Is this simply not possible or is there some way I'm not aware of? Maybe using generics?

With the advent of default methods in Java8's Interfaces are class adapters now possible in Java

Class Adapters uptil now have been considered not possible in java.Previous question regarding the same also says so.

But, Java 8 now supports default methods in Interfaces and multiple interfaces can be implemented by a class. So, a class inheriting from multiple interfaces with multiple default methods can make one interface's default methods act as an adapter and make a call to the other interface's (adaptee's) default method.

So, now is the statement Java 8 supports Class Adapters correct?

Good pattern for grades with different grade systems

I'm making a system that has Exams that can be graded, but the catch is that they can be graded in different grading systems (like A, B, C, D... or percentages or the 12, 10, 7, 4, 02, 00 system we use in Denmark).

I will need some way of doing statistics on the grades, so they cannot simply be stored as Strings.

I want to be able to make new grading systems easily.

I was considering making a IGradeSystem interface and a Grade class (that references the IGradeSystem). That way I can simply make new implementations of the interface for new grade systems. But I don't know if this is a good way to do it.

Any pointers to what pattern I should be using? I'm sure there is a good/accepted way of doing this, and I prefer using patterns when there is one applicable.

usage of Chain of Responsibility

I want to use the pattern Chain of Responsibility to check if a location (Latitude and Longitude) is on a distance. For this purpose I got a boolean which should be true if location is on distance and false if not. Before the pattern - my code looked like this:

    public static boolean OnDistance(MyLocation a, MyLocation b, MyLocation queryPoint) {
    // wenn x von a kleiner ist als b´s
    if (a.mLongitude < b.mLongitude) {
        // nd query dazwischen liegt
        if (b.mLongitude >= queryPoint.mLongitude && queryPoint.mLongitude >= a.mLongitude) {

            if (a.mLatitude > b.mLatitude) {
                if (queryPoint.mLatitude <= a.mLatitude && queryPoint.mLatitude >= b.mLatitude) {
                    System.out.println("ja!");
                    return true;
                }
            }
            if (a.mLatitude < b.mLatitude) {
                if (queryPoint.mLatitude >= a.mLatitude && queryPoint.mLatitude <= b.mLatitude) {

                    System.out.println("ja!");
                    return true;
                }
            }
        }
        {
        }

    }
    // wenn x von b kleiner ist als a´s
    if (b.mLongitude < a.mLongitude) {

        if (queryPoint.mLongitude >= b.mLongitude && queryPoint.mLongitude <= a.mLongitude) {

            if (a.mLatitude > b.mLatitude) {

                if (queryPoint.mLatitude <= a.mLatitude && queryPoint.mLatitude >= b.mLatitude) {
                    System.out.println("ja!");
                    return true;
                }
            }
            if (a.mLatitude < b.mLatitude) {
                if (queryPoint.mLatitude <= b.mLatitude && queryPoint.mLatitude >= a.mLatitude) {
                    System.out.println("ja!");
                    return true;
                }
            }
        }
    }

    System.out.println("leider nichts geworden! . lauf weiter!!!!");
    return false;
}

part of my Chain of Responsibility code (I got four classes like this one):

    public boolean check(MyLocation a, MyLocation b, MyLocation queryPoint) {
    // TODO Auto-generated method stub
    if ((a.mLongitude < b.mLongitude)
            && (b.mLongitude >= queryPoint.mLongitude && queryPoint.mLongitude >= a.mLongitude)
            && (a.mLatitude > b.mLatitude)
            && (queryPoint.mLatitude <= a.mLatitude && queryPoint.mLatitude >= b.mLatitude)) {

        System.out.println("ja, gerne!");
        onDistance = true;
        return true;

    }

    else {
        onDistance = false;
        System.out.println("weiter, lauf doch weiter");
        nextInChain.check(a, b, queryPoint);
    }

    return false;

}}

the code works but because of the "boolean return" it walks through the chain and after that it walks the complete way back to execute this returns.

My Question: First of all - is Chain of Responsibility a suitable way to "replace" this if-statments. And is there a way to stop the chain go back all the way to execute all the returns or rather what can I use instead of this boolean?

Thanks!

DI composition root: how does it ensure compile-time resolution checking

I've read a couple of articles my Mark Seeman on Dependency Injection, specifically the reasons for avoiding the Service Locator pattern:

Basic idea behind Service Locator being problematic is that it can fail at runtime:

public class OrderProcessor : IOrderProcessor
{
    public void Process(Order order)
    {
        var validator = Locator.Resolve<IOrderValidator>();
        if (validator.Validate(order))
        {
            var shipper = Locator.Resolve<IOrderShipper>();
            shipper.Ship(order);
        }
    }
}

var orderProcessor = new OrderProcessor();

// following line fails at compile time if you 
// forget to register all necessary services - and
// you don't have a way of knowing which services it needs

orderProcessor.Process(someOrder);

But this means that the Composition Root must not only resolve all dependencies at startup, but actually instantiate the entire object graph, or otherwise we still wouldn't know it all the necessary dependencies have been registered:

private static void Main(string[] args)
{
    var container = new WindsorContainer();
    container.Kernel.Resolver.AddSubResolver(
        new CollectionResolver(container.Kernel));

    // Register
    container.Register(
        Component.For<IParser>()
            .ImplementedBy<WineInformationParser>(),
        Component.For<IParser>()
            .ImplementedBy<HelpParser>(),
        Component.For<IParseService>()
            .ImplementedBy<CoalescingParserSelector>(),
        Component.For<IWineRepository>()
            .ImplementedBy<SqlWineRepository>(),
        Component.For<IMessageWriter>()
            .ImplementedBy<ConsoleMessageWriter>());

    // Everything must be resolved AND instantiated here
    var ps = container.Resolve<IParseService>();
    ps.Parse(args).CreateCommand().Execute();

    // Release
    container.Release(ps);
    container.Dispose();
}

How feasible is this in a real world application? Does this really mean you are not supposed to instantiate anything anywhere outside the constructor?

lundi 26 octobre 2015

Signal/Slot between classes and Design of Classes

suppose I've the following classes :

class A:public QObject{
    Q_OBJECT
...
signals:
   void sendData(QString data);
}

class B:public QObject{
    Q_OBJECT

  public:
     A a;
...
public slots:
  void onSendData(QString);
signals:
   void  sendData(QString data);
}


class C:public QObject{
    Q_OBJECT

  public:
     B b;
...
public slots:
  void onSendData(QString);
signals:
   void sendData(QString data);
}

.
.
.


class MainWindow:public QMainWindow{
    Q_OBJECT

  public:
     LastClass lc;
public slots:
  void onSendData(QString);//show data on ui
}

class A digs data and when it finds a special data it must send it to ui(mainwindow) , so it calls sendData signal, then class B which contains an instance of A, grabs the signal and from it's slot sends it to above class ,...

as you can see, it causes a recursive signal/slot send and receiving which I doubt that it is a good design.

Is it a correct way or must I change the design ? ( it's hard to change design in some circumstances though). (I cannot use inheritance because each class has a different functionality and different functions.)

Service classes or no service classes?

I am coding a C# WinForms application, and I have a design question in regards to whether I should use Service Classes to generate some output, or if each object should contain all the required functions within each single object, and these functions are called to generate some output.

Either way, the output will be exactly the same. The output is a text file.

Here is the situation:

I have an object that has a lot of user data in the form of multiple custom objects. I am then creating multiple types of output objects. Preview objects, output to directory objects are two examples. Each of these output objects handle the data and place this data in a suitable output form. The data is then finally outputted as a string.

Should I use a service class to create the suitable output, where the service class has multiple functions that create the correct output, or should each of the objects that I am using have their own functions that generate the data in the correct output format?

Is there a design pattern that I should be aware of in making this decision, and if so, can someone please point me in the correct direction for this? Also, I am keen to hear on peoples thoughts of whether it is good practice to use service classes, or nested object functions to generate output.

Thanks.

How to differenciate similar objects in Java without getClass()?

I am making a simple game un Java and I think I have a design problem. I have an abstract class Unit that have all units' behaviour (like move(), attack(), getHealth(), ...). Then I extend three classes from Unit: Archer, Lancer, Rider. Each one of those only have a constructor to differenciate them, because they behave exactly the same way but have different stats.

public class Archer extends Unit {    
    public Archer(World world, Location location, Player owner) {
        super(new Attack(1, 6, 1), new Defense(1, 4, 2), 10, 4, location, owner);
    }
}

public class Lancer extends Unit {    
    public Lancer(World world, Location location, Player owner){
        super(new Attack(2, 2, 5), new Defense(3,2,3), 15, 5, location, owner);
    }
}

public class Rider extends Unit{    
    public Rider(World world, Location location, Player owner) {
        super(new Attack(3, 2, 4), new Defense(2,4,1), 15, 7, location, owner);
    }
}

Now comes the problem. I want to be able to print those units with different sprites, so I make ArcherUI, LancerUI and RiderUI classes that have each sprite. But how do I tell the program to print for example an Archer?

A solution might be do a getClass() for every Unit, but it isn't a good one since I want a good object oriented design.

An other option that came into my mind was to add a name to the unit like that:

public class Archer extends Unit {  
    String name = "archer";
    public Archer(World world, Location location, Player owner) {
        super(new Attack(1, 6, 1), new Defense(1, 4, 2), 10, 4, location, owner);
    }
}

but then comparing this String would be the same as making a getClass(). What can I do? Is there any idea? or any pattern?

Design pattern usage in a java project

I am working on a java project that requires us to use pattern patterns.

Me and my team is relatively inexperienced in using design patterns so we can't figure out what the best design pattern would be to use.

Our project is basically supposed to track financial portfolios with stock and accounts.

Here is the description of the project: http://ift.tt/1LYfMo0

By taking a brief look at the description of the project, can you think of some patterns that would be ideal for such a project?

DESIGN PATTERN and xml

I came across a programming assignment on using design patterns.The input is to be derived from a xml file and the information should be used with design patterns like factory and abstract factory.I used the DOM parser to get the data from an XML file but I am clueless about what needs to be done next.Any help would be appreciated.Thanks :)

Design pattern for including errors with return values

I'm writing an add-in for another piece of software through its API. The classes returned by the API can only be access through the native software and the API. So I am writing my own stand alone POCO/DTO objects which map to the API classes. I'm working on a feature which will read in a native file, and return a collection of these POCO objects which I can stole elsewhere. Currently I'm using JSON.NET to serialize these classes to JSON if that matters.

For example I might have a DTO like this

public class MyPersonDTO
{
    public string Name {get; set;}
    public string Age {get; set;}
    public string Address {get; set;}       
}

..and a method like this to read the native "Persons" into my DTO objects

public static class MyDocReader
{
    public static IList<MyPersonDTO> GetPersons(NativeDocument doc)
    {
        //Code to read Persons from doc and return MyPersonDTOs
    }
}

I have unit tests setup with a test file, however I keep running into unexpected problems when running my export on other files. Sometimes native objects will have unexpected values, or there will be flat out bugs in the API which throw exceptions when there is no reason to.

Currently when something "exceptional" happens I just log the exception and the export fails. But I've decided that I'd rather export what I can, and record the errors somewhere.

The easiest option would be to just log and swallow the exceptions and return what I can, however then there would be no way for my calling code to know when there was a problem.

One option I'm considering is returning a dictionary of errors as a separate out parameter. The key would identify the property which could not be read, and the value would contain the details of the exception/error.

public static class MyDocReader
{
    public static IList<MyPersonDTO> persons GetPersons(NativeDocument doc, out IDictionary<string, string> errors)
    {
        //Code to read persons from doc
    }
}

Alternatively I was also considering just storing the errors in the return object itself. This inflates the size of my object, but has the added benefit of storing the errors directly with my objects. So later if someone's export generates an error, I don't have to worry about tracking down the correct log file on their computer.

public class MyPersonDTO
{
    public string Name {get; set;}
    public string Age {get; set;}
    public string Address {get; set;}

    public IDictionary<string, string> Errors {get; set;}   
}

How is this typically handled? Is there another option for reporting the errors along with the return values that I'm not considering?

Architectual pattern for CLI tool

I am going to write some HTTP (REST) client in Python. This will be a Command Line Interface tool with no gui. I won't use any business logic objects, no database, just using an API to communicate with the server (using Curl). Would you recommend me some architectual patterns for doing that, except for Model View Controller?

Note: I am not asking for a design patterns like Command or Strategy. I just want to know how to segregate and decouple abstraction layers.

I think using MVC is pointless regarding the fact of not having a business logic - please correct me if I'm wrong. Please give me your suggestions!

Do you know any examples of CLI projects (in any language, not necessarily in Python) that are well maintained and with clean code?

Cheers

Design pattern to follow in board game developing [on hold]

I'm developing a digital board game (C# + Unity) in which the player's character walk over board tiles to gather resources. Also, each tile triggers certain rules when reached. So far this has been coded and is beautifully working.

Trick is, as the game progresses those tiles will get minor rule changes due to spells and curses. I am now trying to get my head around what pattern to stick with. Even though I've never used Interfaces before, by reading about it, I'm becoming quite inclined to go with them, a I'll be able to implement new rules/methods further on. I presume that once coded, it will make it easier to use them in future levels and scenes too.

Will using interfaces really be as helpful as I think in this case?

EF4 how to support inherited Entities, does EF5 support this?

Scenario:

I'm using EF4.

I have 3 entities in my EF context, Employee, HourlyEmployee inherit Employee, SalariedEmployee inherit Employee. Code first created one table and with a discriminator column.

Due to 3 of them are treated separately most of time, and for easy db manage, I thought split them to three tables by set entity mapping in OnModelCreating method. (Bad idea.)

Now whenever I load two different types of entities with same ID, EF complains with error "all objects in the entityset must have unique primary keys....", kind of like this issue: Entity framework and inheritance: NotSupportedException

I can only think of two solutions but don't know which one is doable, and if there is miracle work around for this issue? So I can keep 3 tables and inheritance.

  1. remove inheritance, 3 stand alone entities. So I can keep 3 tables.
  2. remove the entity mapping in OnModelCreating, so I end up with one table.
  3. .....??????

Also, does EF5 support these kind of inheritance and entity mapping to different table without discriminator column?

Thanks a lot for reading.

Is it okay to use a friend class, to reduce complexity of mediator class?

According to GoF,

The complexity of WidgetChanged increases proportionally with the complexity of the dialog. Large dialogs are undesirable for other reasons, of course, but mediator complexity might mitigate the pattern’s benefits in other applications.

Here is book excerpt : https://goo.gl/mO1ydZ

So, can we delegate the handling of events related to helper class of Mediator, like this, to reduce the complexity of Mediator?

void FontDailogDirector::WidgetChanged(Widget * theChangedWidget)
{
    HelperofFontDialogDirector(theChangedWidget);
}

Is it good design? I am noob to design patterns. Thank you.

Command object only in controller or could it be passed to service layer?

In grails framework I saw the command object pattern but its use is not very clear for me. In addition most of examples given by grails documentation are about domain classes not command objects (maybe to simplify code example).

1 - Command object is something used between view and controller layer and must stay there ?

2 - Or is it a good practice to pass command object to service layer ?

To illustrate point 2 :

class MyController {

    def updateUserPassword (UserPasswordCommand cmd) {
        ...
        myService.updatePassword(cmd)
        ...
    }
}

If point 2 is a bad practice, then how do you pass submitted data to the service layer ? Via domain class ?

How to handle relationships in a REST api

I am trying to get my head around how to handle relationships in REST.

I have read this thread: How to handle many-to-many relationships in a RESTful API?

If I have Drivers and Cars in my api and a Driver can only exist if connected to a Car I would make Drivers a subresource in Cars. The relationship between a Car and a Driver contains a set of properties, say averageSpeed and timeOnTheRoad. One Car can have many Drivers, but a Driver can only have one Car.

How should I add a new driver? How should I add a relationship between a driver and a car?

If I add a resource Wunderbaums which is not a subresource to Cars, but a Car can contain Wunderbaums. How should I add a relationship between a Car and a Wunderbaum?

One way of adding a relationship between two entities is to POST to /entityA/{id}/entityB/{id} and send properties for the relationship in the body. This would work for my example with Cars and Wunderbaums since Wunderbaums is not a subresource of Cars, but it would not work in my example with Cars and Drivers since it would interfere with CRUD functionality for Drivers.

How to do OOP and MVC properly PHP [on hold]

I've been programming with PHP for a few years and I still don't know how to implement OOP and MVC properly.

I'll put an example of a project that I'm currently developing in Laravel. I have an online library. I have a controller for each section. Something like Authors Controller, in that controller I have all the function related with that section. But this is opposite to the Single Responsibility Principle. I think that is not useful to create a controller for each task like show authors, another for create author, another for get books of the author, and that stuff. Now I'm trying to implement TDD and I'm not sure how to do it if my classes have no SRP. The problem with the section organization is that I don't "need" to use varibles in the class, I have enough with local variables.

Here is my showAuthor function in AuthorController

public function mostrarAutor($id)
{
    $autor = Autor::find($id);
    $libros=$autor->libros;
    $siguiendo=Auth::user()->autores_siguiendo()->where('autor_id','=',$autor->id)->first();
    $atribuciones=$autor->atribuciones()->get();
    $guardado=0;
    if ($siguiendo) $guardado=1;
    return $this->mostrarVista(View::make(Config::get('rv.autor'), array('autor' => $autor, 'libros' => $libros, 'guardado' => $guardado, 'atribuciones' => $atribuciones)));
}

I can't use polymorphism because I would need to instantiate classes and with the route system of MVC I never do that. I just

Route::get('/autor/{id}', 'AutorController@mostrarAutor')->where('id', '[0-9]+');

Like this I have more showAuthor functions like showAuthors, showAuthorsYouAreFollowing or ShowAuthorOfBook.

If the question isn't clear I'll say that I ask if someone can explain for AuthorsController which is a right way to implement OOP in Laravel.

Greetings and thank you very much.

Design pattern: create one object per class

I want to create one object per class type, like for example the Logger class of Apache [1] that creates a new Logger instance if there is no instance for your class otherwise it gives you a new one.

I am thinking of this kind of class factory:

public class Logger {

    private String TAG;//the class name   
    private static HashMap<String, Logger> loggerList = new HashMap<String, Logger>();

    private Logger(String className){
        TAG="["+className+"]";
    }

    public static Logger getLogger(String className){
        Logger logger= loggerList.get(className);
        if( logger != null){
            return logger;
        }else{
            logger= new Logger(className);
            loggerList.put(className, logger);
            return (logger);
        }       
    }

I don't know if this is the best way to do it. Is there another way more optimised?

[1]http://ift.tt/1GsCiVC

WinForms - grouping controls in collection - MVP

BACKGROUND

I am trying to write simple WinForms application, using MVP structure in my project. Now I am trying to bind lists to group of ComboBoxes. My form looks like this:

enter image description here

It implements interface IMaterialDatabasePropertiesView:

public interface IMaterialDatabasePropertiesView
{
    MaterialDatabasePropertiesPresenter Presenter { set; }

    List<string> ElementsList1st { get; set; }
    int SelectedElement1st { get; set; }

    List<string> ElementsList2nd { get; set; }
    int SelectedElement2nd { get; set; }
    .
    .
    //etc... until 14th elementh is reached
}

Implementation of that intefrace is very simple:

public partial class MaterialDatabasePropertiesForm : Form, IMaterialDatabasePropertiesView
{
    public MaterialDatabasePropertiesPresenter Presenter { private get; set; }

    public List<string> ElementsList1st
    {
        get { return this.comboBox1st.DataSource as List<string>;  }
        set { this.comboBox1st.DataSource = value;  }
    }
    public int SelectedElement1st
    {
        get { return this.comboBox1st.SelectedIndex; }
        set { this.comboBox1st.SelectedIndex = value; }
    }

    public List<string> ElementsList2nd
    {
        get { return this.comboBox2nd.DataSource as List<string>;  }
        set { this.comboBox2nd.DataSource = value; }
    }
    public int SelectedElement2nd
    {
        get { return this.comboBox2nd.SelectedIndex; }
        set { this.comboBox2nd.SelectedIndex = value; }
    }
    .
    .
    //etc... until 14th elementh is reached
}

What I want to do is binding to each comboBox list of that Enum:

public class MaterialDatabasePropertiesPresenter
{
        private readonly IMaterialDatabasePropertiesView _view;
        private List<FormComboBox> ComboBoxes;

        public enum OfElement
        {
            C, Si, Mn, P, S,
            N, Cr, Mo, Nb, Ni,
            Ti, Al, V, Cu
        }

private List<OfElement> listOfElements = Enum.GetValues(typeof(OfElement))
                                 .Cast<OfElement>()
                                 .ToList();
}


PROBLEM DESCRIPTION

What I need to do is bind that list to each comboBox under certain cimcurstances:

1) If no comboBox is filled you can choose from all enums.

2) If some comboBox is set to some specific enum, another no should not let me to choose the same enum (simply it shouldn' t even appear on list of avalible options in comboBox

Now I am trying to all of these controls in one list, or any other kind of Collection, so it would make my task easier. I created this class:

private class FormComboBox
    {
        public FormComboBox(List<string> avalibleElements, int currentIndex)
        {
            AvalibleElements = avalibleElements;
            CurrentIndex = currentIndex;
        }

        public List<string> AvalibleElements;
        public int CurrentIndex;
    }

And put List<FormComboBox> ComboBoxes; as property in my Presenter class. I Initialize it like that:

private void InitializeComboBoxesProperty()
        {
            ComboBoxes = new List<FormComboBox>()
            {
                new FormComboBox(_view.ElementsList1st, _view.SelectedElement1st),
                new FormComboBox(_view.ElementsList2nd, _view.SelectedElement2nd),
                .
                .
                //etc. till 14th comboBox
            };
        }

Of course when I change some element of ComboBox list it only changes that element, and has no influence on my _view.ElementList1st or any other.


Conclusion

To sum up - as you can see I am a bit lost, so I hope you can help me find some solution. To stay clear - I am looking for some kind of design pattern, or something similar, that would let me to group my controls in some collection. Cheers!

Does it belong to controller or model?

I have this before_action method :

  def convert_duration_reminder
    allowed_duration_units = %(hour day)
    if allowed_duration_units.include? params[:store][:store_setting_attributes][:reminder_unit]
      store_settings_params = params[:store][:store_setting_attributes]
      @duration_reminder = store_settings_params[:reminder_duration].to_i.send(store_settings_params[:reminder_unit]).to_i / 3600
    else
      redirect_to store_settings_store_path(id: current_store.id)
    end
  end

I have a little bit of logic inside. The @duration_reminder is after used in an update_attributes.

Does it belongs to controller ? For me yes because I'm using params and I have a redirect and methods are short (except line length...) and doesn't process any data in database.

This method simply convert times in minutes according to what the user choose in the view ("2 hours", "1 day").

From the book Rails 4 action, it's write :

■ Models contain the domain logic of your application. This logic dictates how the records in your database are retrieved, validated, or manipulated. In Rails appli- cations, models define the code that interacts with the database’s tables to retrieve and set information in them. Domain logic also includes things such as validations or particular actions to be performed on the data.

■ Controllers interact with the models to gather information to send to the view. They’re the layer between the user and the database. They call methods on the model classes, which can return single objects representing rows in the data- base or collections (arrays) of these objects. Controllers then make these objects available to the view through instance variables. Controllers are also used for permission checking, such as ensuring that only users who have special permission to perform certain actions can perform those actions, and users without that permission can’t.

Does def convert_duration_reminder belongs to controller ?

Alternative to singleton wrapping native C library calls

In my application I'm writing an abstraction layer on top of a JNI library that calls into native C code. This native library (FFmpeg to be exact) exposes some global functions to change logging behavior.

In particular, I'm using a callback that forwards log messages to custom handlers. The problem is that there can be only one such callback. Creating a new instance of this callback means the native library will call it instead, whether it has been registered as the new callback or not. If you want another then you have to create a different callback class just like you'd declare a new function in C.

To me there seems to be two alternatives:

(1) Allow multiple instances of this singleton class. I'm already using a private static instance of the callback class. It cannot be instantiated elsewhere, at least, my subclass of this callback.

(2) Some other way to restrict users from instantiating this singleton class more than once.

The issues I have with the first approach are:

(1) The API is misleading. It's simply a proxy object that operates on global state. Yet to the user, it seems like each instance operates on its own state.

(2) Synchronization. I cannot use multiple locks. Using a static private lock takes us back to issue #1. At least a lock cannot be mutated of course.

Should I just give up on the whole thing and use a singleton anyway? No matter how you cut it, the class will be mutating global state. It's just that this state is beyond my control.

What to do in such situations? Do I have any viable alternatives?

dimanche 25 octobre 2015

best workaround where cant extend abstract enum java?

I have a DrivingSimulation class that implements a Simulation interface.
A Router gets the correct route from the Simulation implementation.
Thus the DrivingSimulation has a DrivingSimulationRoutes, that is implemented with an enum Route. But i cant extend the abstract Routes or implement an Routes interface and return the DrivingSimulationRoutes.Route as a Simulation.Route because enum is already extended in java.

What is the best pattern to solve this problem of wanting to ensure SimulationImplementationRoutes has an enumerable number of routes?

Design patterns Magento 2

Magento is a pretty complex application. And knowing as a large open source ecommerce platform. Throughout Magento 1 architecture, it commonly used 12 design patterns which allows developers to view and use them in real.

As you know, Magento 2 is coming soon. I really want to know what patterns are approved? And give us some examples?

Implement callbacks for game state methods

In my game engine I want to have start() and update() callback methods much like in Unity3D. They will form 'GameListener' interface, which the user should implement to get to them. How do I implement these callbacks without adding any listeners? For example, in libGDX, you have to implement ApplicationListener interface to get access to render() and start() methods without adding any listeners.

How does Dependency Injection using ServiceLocator advantageous over creating dependent objects explicity in constructor

It is possible to resolve the dependency by having a default constructor initializing the dependent object as below.

public class Foo:IFoo
{
public void disp()
{
//some code
}
}

public class MyClass
{
    IFoo ifoo;

    public MyClass()
    {
     this(new Foo());
    }

    public  MyClass(IFoo i)
    {
      this.ifoo = i;
    }

    void method1()
    {
     ifoo.disp();
    }
}

Similarly, all dependencies could be resolved by having 2 constructors as above, with which the unit testing framework could use the parameterized constructor straight away.

In this case, what is the advantage of implementing IunityContainer and service locator to create an instance.

Encapsulating iOS logic

I am creating a UITextField that will format numbers. My initial thought was that I would subclass UITextField and the logic to format the numbers would be added to this subclass. My thinking is that this logic has nothing to do with my main ViewController and it should be encapsulated into the control itself.

So now I have a subclass. All I need to do now is listen for an event such as - (BOOL)textField: shouldChangeCharactersInRange: replacementString:.

However it seems that setting the delegate to self is not good design practice, which I have to say I was a little surprised. It makes complete sense to me to encapsulate the control logic in the subclass rather than a view controller or a completely separate class.

My current approach is to add a target action to the UITextField which listens for any changes - but this doesn't feel right. I want to use the delegate but it seems that's frowned upon.

So if delegate methods are only meant to be handed off to other objects, how are objects supposed to encapsulate logic related to those events, without using notifications or KVO or similar?

Why should the handling of events be handed off to say a ViewController when really it's the control that should handle that logic?

Avoiding starvation with a C++ notify_all()

My barrier synchronisation scenario is this:

a. Threads take a step forward in synchronisation - i.e. they complete one unit of task and then wait for all the other threads to do the same, then when they do, they can move forward again.

b. I have a large number of threads (around 256) waiting on a condition variable. When the condition is met a notify_all() will be sent.

c. (Part where starvation risk arises): Immediately before the notify_all() is called, a runnable variable is set to true and a counter - completed - is set to zero. When a thread completes its task unit, it calls a function which first sets runnable to false, then increments the completed variable - the condition is met when completed equals the threshold (namely the number of threads that need to complete a task unit), where upon runnable is set to true.

I.e., we wait like this:

cond.wait(lck, runnable == true);

And have this:

unique_lock<mutex> lck(runMut);
runnable = true;
cond.notify_all();

My concern is that any woken thread could complete its task and then call into the wait() function before a thread further down the chain has been woken. When this "lower" thread tests runnable, it will find it set to false and so go back to sleep.

Is there a design pattern or some other way I can get round this?