vendredi 30 septembre 2016

Apply design Patterns to android with firebase application

I want to apply design pattern to my application. I think to divide it by this categories: My code separation

Where:

  1. LoginListener : implements the listener for the activity
  2. LoginNetwork : is the class where i want to execute the firebase code
  3. LoginNetworkListener : is the class where i want to insert the code for the firebase listener
  4. LoginLogic : is the class where i insert the code for initialize the googleSignIn for my application ( and the request permission )
  5. LoginController : there isn't code here
  6. LoginSignleton : is Singleton for all data necessary between the other Login classes.

This is my code: LoginActiivity:

public class LoginActivity extends AppCompatActivity {

    private final static String TAG = "Login Activity";
    private final static int RC_SIGN_IN = 9000;

    private Button continueNoLogin;
    private SignInButton googleLogin;

    private LoginNetwork loginNetwork;
    private LoginSingleton loginSingleton;
    private LoginLogic loginLogic;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        FirebaseApp.initializeApp(this);
        continueNoLogin = (Button) findViewById(R.id.login_unregistered);
        googleLogin = (SignInButton) findViewById(R.id.login_registered_google);
        loginNetwork = new LoginNetwork();
        loginSingleton = LoginSingleton.getInstance();
        loginLogic = new LoginLogic(this);
    }

    @Override
    protected void onStart() {
        super.onStart();
        LoginListener loginListener = new LoginListener();
        continueNoLogin.setOnClickListener(loginListener);
        googleLogin.setOnClickListener(loginListener);
    }

    public void startLoginResultActivity(){
        Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(LoginSingleton.getInstance().getGoogleApiClient());
        startActivityForResult(signInIntent,RC_SIGN_IN);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.d(TAG,"OnActivityResult");
        // Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
        if (requestCode == RC_SIGN_IN) {
            Log.d(TAG,"RC_SIGN_IN");
            GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
            if (result.isSuccess()) {
                Log.d(TAG,"google signin successfull");
                // Google Sign In was successful, authenticate with Firebase

            } else {
                Log.d(TAG,"SignInWithGoogle Failed " + result.getStatus());
                // Google Sign In failed, update UI appropriately

            }
        }
    }
}

LoginListener:

public class LoginListener implements View.OnClickListener,GoogleApiClient.OnConnectionFailedListener {

    private final static String TAG = "LoginListener";



    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.login_unregistered:

                break;
            case R.id.login_registered_google:
                Log.d(TAG,"Ho ricevuto l'intent");
                LoginActivity loginActivity = new LoginActivity();
                loginActivity.startLoginResultActivity();
                break;
        }
    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

    }
}

LoginSingleton:

public class LoginSingleton {

    private GoogleApiClient googleApiClient;
    private GoogleSignInOptions googleSignInOptions;

    private static LoginSingleton ourInstance = new LoginSingleton();

    public static LoginSingleton getInstance() {
        return ourInstance;
    }

    private LoginSingleton() {
    }

    public void setGoogleApiClient(GoogleApiClient googleApiClient) {
        this.googleApiClient = googleApiClient;
    }

    public GoogleApiClient getGoogleApiClient() {
        return googleApiClient;
    }

    public void setGoogleSignInOptions(GoogleSignInOptions googleSignInOptions) {
        this.googleSignInOptions = googleSignInOptions;
    }

    public GoogleSignInOptions getGoogleSignInOptions() {
        return googleSignInOptions;
    }
}

LoginNetwork:

public class LoginNetwork  {

    private final static String TAG = "LoginNetwork";

    private FirebaseAuth firebaseAuth;


    public LoginNetwork(){

        // Init FirebaseAuth
        firebaseAuth = FirebaseAuth.getInstance();

        // generate listener
        LoginNetworkListener loginNetworkListener = new LoginNetworkListener();

        firebaseAuth.addAuthStateListener(loginNetworkListener);

    }

}

LoginNetworkListener:

public class LoginNetworkListener implements FirebaseAuth.AuthStateListener {

    private final static String TAG = "LoginNetworkListener";

    @Override
    public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {

        if (firebaseAuth.getCurrentUser() != null){
            Log.d(TAG,firebaseAuth.getCurrentUser().toString()+"is signedIn");
        } else {
            Log.d(TAG,"User is signedOut");
        }

    }
}

LoginLogic:

public class LoginLogic {

    private final static String TAG = "LoginLogic";

    private GoogleApiClient googleApiClient;
    private GoogleSignInOptions googleSignInOptions;

    public LoginLogic(AppCompatActivity activity){

        LoginListener loginListener = new LoginListener();
        /*
        * Configure Google Signin
        */
        LoginSingleton.getInstance().setGoogleSignInOptions(new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestIdToken("571158992107-7bifs7qrivnqpkk77gmmoko9rkg73c0d.apps.googleusercontent.com").requestEmail().build());

        LoginSingleton.getInstance().setGoogleApiClient(new GoogleApiClient.Builder(activity).enableAutoManage(activity,loginListener).build());
    }
}

When i start the application it give me this error:

FATAL EXCEPTION: main                                                                                                    Process: it.unisalento.progetto.software.cunamameli.dafb, PID: 24354                                                                            java.lang.RuntimeException: Unable to start activity ComponentInfo{http://ift.tt/2dGLObD}: java.lang.IllegalStateException: Default FirebaseApp is not initialized in this process it.unisalento.progetto.software.cunamameli.dafb. Make sure to call FirebaseApp.initializeApp(Context) first.                                     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2456)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2539)
at android.app.ActivityThread.access$900(ActivityThread.java:159)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1384)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:152)
at android.app.ActivityThread.main(ActivityThread.java:5507)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.IllegalStateException: Default FirebaseApp is not initialized in this process it.unisalento.progetto.software.cunamameli.dafb. Make sure to call FirebaseApp.initializeApp(Context) first.
at com.google.firebase.FirebaseApp.getInstance(Unknown Source)
at com.google.firebase.auth.FirebaseAuth.getInstance(Unknown Source)
at it.unisalento.progetto.software.cunamameli.dafb.loginPack.LoginNetwork.<init>(LoginNetwork.java:19)
at it.unisalento.progetto.software.cunamameli.dafb.loginPack.LoginActivity.onCreate(LoginActivity.java:35)
at android.app.Activity.performCreate(Activity.java:6304)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2409)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2539) 
at android.app.ActivityThread.access$900(ActivityThread.java:159) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1384) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:152) 
at android.app.ActivityThread.main(ActivityThread.java:5507) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

Where:

LoginNetwork.java:19 is -> firebaseAuth = FirebaseAuth.getInstance();

and

LoginActivity.java:35 is -> loginNetwork = new LoginNetwork();

I don't understand the where is the error. Please help me. Thanks a lot!

Which design pattern to use in the scenario where object type is unknown and I have to check the object type?

I have the scenario below where a service layer call returns objects of type DistributionPrompt, MentoringPathPrompt, BossLetterPrompt, and CertificatePrompt in an object[]. I've managed to localize this checking to a single function but I feel as if this is not an elegant solution but I'm not quite sure which design pattern I can apply that would be ideal for this scenario.

Could someone let me know the design pattern name that I can use for this situation? I don't need the final solution as I'd like to work it out myself but just the name would suffice as I don't know design patterns as well as I should. Also, please explain how this design pattern would be more useful compared to the existing function if another Prompt type were introduced?

private static PromptVisibility ParsePrompts(IEnumerable prompts)
        {
            var promptVisibility = new PromptVisibility();

            foreach (var t in prompts)
            {

                if (t is DistributionPrompt)
                {
                    promptVisibility.IsDistributionPromptVisible = true;
                    promptVisibility.DistributionNumber = ((DistributionPrompt)t).DistributionNumber;
                }

                if (t is MentoringPathPrompt)
                {
                    promptVisibility.IsMentoringPathPromptVisible = true;
                }

                if (t is BossLetterPrompt)
                {
                    promptVisibility.IsBossLetterPromptVisible = true;
                    promptVisibility.EmployerAddress = ((BossLetterPrompt)t).ExistingEmployerAddress;
                }

                if (t is CertificatePrompt)
                {
                    promptVisibility.IsCertificationPromptVisible = true;
                }
            }

            return promptVisibility;
        }

Example on how to use a container for DI?

I have read countless of posts about dependency injection and I really want to follow the "pure constructor way" of doing things. However I was thinking about the following and im not sure if its the right way:

  • Create a class that is a singleton and name it inject manager.
  • Manager has many private fields with all the instantiated dependencies.
  • dependencies can be called via getters.

Honestly I have no idea what to do. I want a technique can be used to set up a class that manages all my dependencies?

A simple example with explanation would be great. Im really interested in learning how this works. I heared its also possible with an interface but I couldnt find any examples.

Dynamic method binding with inheritance in Python

I am new to python (~ a month), and I wish I had switched to it sooner (after years of perl). I wanted to know if there was a popular design pattern that I could use instead of the below, or if this already has a design pattern name (I sadly have no formal CS background, and knowing this will help my documentation).

I have a class hierarchy (as of now, 26 of them with 3 base classes). Only the base classes have some trivial methods (eg: add_child), and each derived class only extends the base class with new data attributes (specific to the derived class), overriding methods when necessary (eg: __str__).

Assume the code for the classes can not be edited, but the classes can be extended with methods during runtime (like Visitor Pattern). Therefore the module that has all the class definitions remains clean and minimal. There exists another module that contains various functions which can be bound to the classes during runtime.

I am dealing with tree(s) where nodes are of different classes. Yet, the nodes have the same method names, thereby allowing easy/blind iterator operation. Each method may do something different (like polymorphism). These methods are dynamically assigned to classes, based on what module gets loaded. The method is inherited, unless overridden.

# asttypes.py
class ASTNode(object):

    def __init__(self, level, linenum, tag):
        self.children = []
        self.level = level
        self.linenum = linenum
        self.tag = tag
        self.nodetype = self.__class__.__name__

    def add_child(self, node):
        self.children.append(node)

    def __str__(self):
        return "[{}] {}".format(self.tag, self.nodetype)


class ASTVar(ASTNode):

    def __init__(self, level, linenum, tag, name, vartype, width):
        ASTNode.__init__(self, level, linenum, tag)
        self.name = name
        self.vartype = vartype
        self.width = width

    def __str__(self):
        return "[{}] {}: {}, {} of width {}".format(self.tag, self.nodetype, self.name, self.vartype, self.width)

I primarily wanted to grant specific abilities (methods) to each of the classes, yet, be able to call them using the same name. Note, in below example the iteration/recursion method call name is different from the function name.

Initially, I implemented this using the Visitor Pattern. But, then realized I didn't really have to, considering I was working in Python.

#astmethods.py
def generic__print_tree(self, level=1):
    """
    Desc: print nodes with indentation
    Target: Any tree node
    """
    print("{}> {}".format('-' * level, self))
    for child in self.children:
            child.print_tree((level + 1))


def ASTNode__stringify(self):
    """
    Desc: Return string representation of the tree under this node
    Target: AST/CFG nodes
    """
    text = str(self)
    for child in self.children:
            text += ", { " + child.stringify() + " }"
    return text

Finally one of the main modules has this function, extend_types() which gets called during module init. There are multiple functionally exclusive main modules, and each has its own extend_types(), because the nodes are expected to do different things, within the context of this module. The methods are inherited, unless overridden.

The main modules are not expected to be imported at the same time. If these modules were to be used at the same time, then the hasattr() check would need to be removed, and the modules' extend_types() would be first called internally within the module functions.

You can see how this extends to having a different eval() (instrument the predicate per CFG block) or emitC() (print C code equivalent) method per class.

# doSomethingCoolWithVerilatorASTDumps.py
def extend_types():
    """
    Upgrade the AST node classes with neat functions
    """
    if not hasattr(ASTNode, 'print_tree'):
        ASTNode.print_tree = generic__print_tree

    if not hasattr(ASTNode, 'transform_controlFlow'):
        ASTNode.transform_controlFlow = ASTNode__transform_controlFlow

    if not hasattr(ASTNode, 'stringify'):
        ASTNode.stringify = ASTNode__stringify

    if not hasattr(ASTNode, 'tidy'):
        ASTNode.tidy = ASTNode__tidy

    if not hasattr(SimpleNode, 'print_tree'):
        SimpleNode.print_tree = generic__print_tree

Composite design pattern in Python with IoC

It is said that Python does not need an IoC container. However, all answers there pay attention on replacing one implementation with another and ignore the fact that this is not the only purpose of the DI.

How to create a composite that automatically receives all its leaves in runtime in a pythonic way?

If I were not clear enough, take a look at this Java & Spring example:

interface PermissionEvaluator {
    boolean isAllowed(User who, Action what);
}    

interface PermissionVoter extends PermissionEvaluator {}

@Service
@Primary
class CompositePermissionEvaluator implements PermissionEvaluator {
    @Autowired
    private List<PermissionVoter> voters;

    public boolean isAllowed(User who, Action what) {
        for (PermissionVoter voter : voters) {
            if (voter.isAllowed(who, what)) {
                return true;
            }
        }
        return false;
    }
}

@Component
@Order(2)
class PermissionVoter1 implements PermissionVoter { /* ... */ }

@Component
@Order(3)
class PermissionVoter2 implements PermissionVoter { /* ... */ }

@Component
@Order(1)
class PermissionVoter3 implements PermissionVoter { /* ... */ }

JavaScript Design Patterns to call same function name across different JavaScript module code objects?

I am building a JavaScript application which will have plugin/modules which will all have a set of mandatory functions shared among each module's code base.

For example, all the modules might have a function named loadSidebarJsonData()

There will also be a base/core app which runs the show/app.

The apps UI will have an app selector DIV in which a user can select an available module which will trigger a click event handler in the core app code.

In this click event handler I need to be able to run a set of functions on the JavaScript object belong to the selected module.

If the Bookmarks app is selected then I need to run loadSidebarJsonData() on the Bookmarks JavaScript object.

If the Notebooks module is selected then it needs to run the loadSidebarJsonData() function on the Notebooks JavaScript object instead.

So inside my core apps JavaScript click event handler I will have access to the name of the clicked on module.

Using that module name, how could I structure my code to have it then call functions on that JS object with the name which will be stored in a string variable when the click event occurs?

Design Pattern Suggestion for Sending Emails for Simple Workflow

I need a design pattern suggestion (.net/c#/mvc) for sending out Emails on for different events. For example in the system i am building

User Registers-Send Email

User Signs up for Newsletter - Send Email

User gets notified for Sending on their Behalf -Send Email

User Deletes Account -Send Email (a lot more scenarios)

What is a good design pattern to use in such cases?

Trading System Design [on hold]

I was asked this question in the interview. We have to design this trading system. So say you have placed an order of 20 shares of APPLE. The trade is not yet processed. You place another order of 30 more shares of APPLE. They both go as the same trade. Now there are many such customers like you who are placing such orders. Moreover, the trades such as 20 shares of APPLE and 30 more shared of APPLE would be executed in serialized fashion. Also, there would be multiple threads to execute trades in parallel so that the whole process is fast. What data structure do you recommend for the trade data ?

I suggested arraylist or queue. To this the interviewer replied that if the trade would have to be executed in thread, then one might thread might get the order of 20 shares of APPLE, and the other one gets the order of 30 shares of APPLE. I was not sure of this and so the interview ended abruptly.

Could you please help me with this data structure question?

Is there a Design Pattern for Data Object structures that frequently change?

Is there a Design Pattern for Data Object structures that frequently change?

I am refactoring a Genetic Algorithm where the structure of the Chromosomes (number of genes, type of genes and boundary of genes) change from problem to problem. For example:

One problem may use

class Chromosome{
    double gene1;  // 0.0 < gene1 < 100.0
    double gene2;  // -7.3 < gene2 < 9.0
}

Another problem may use

class Chromosome{
    int gene1;      // 200 < gene1 < 1000
    double gene2;  // 50.0 < gene2
    double gene3;  // gene3 < -5.0
}

Currently the chromosome structure is hard coded and is difficult to modify for a new problem. I am considering modifying the Strategy Pattern for chromosome changes, unless someone has a better idea.

What OOP patterns can be used to implement a process over multiple "step" classes?

In OOP everything is an object with own attributes and methods. However, often you want to run a process that spans over multiple steps that need to be run in sequence. For example, you might need to download an XML file, parse it and run business actions accordingly. This includes at least three steps: downloading, unmarshalling, interpreting the decoded request.

In a really bad design you would do this all in one method. In a slightly better design you would put the single steps into methods or, much better, new classes. Since you want to test and reuse the single classes, they shouldn't know about each other. In my case, a central control class runs them all in sequence, taking the output of one step and passing it to the next. I noticed that such control-and-command classes tend to grow quickly and are rather not flexible or extendible.

My question therefore is: what OOP patterns can be used to implement a business process and when to apply which one?


My research so far:

The mediator pattern seems to be what I'm using right now, but some definitions say it's only managing "peer" classes. I'm not sure it applies to a chain of isolated steps.

You could probably call it a strategy pattern when more than one of the aforementioned mediators is used. I guess this would solve the problem of the mediator not being very flexible.

Using events (probably related to the Chain of Responsibility pattern) I could make the single steps listen for special events and send different events. This way the pipeline is super-flexible, but also hard to follow and to control.

Looking For Design Patterns

I am looking for design patterns(Singleton,Mediator,Observer,Factory,Provider etc). The main problem is, in the internet content:

Sites are teaching the patterns logic but not the cases. Learning pattern is important but using them conveniently(When and which case) is more important. I am asking for the useful content which indicates the use cases of the patterns and detailed information about designing the architecture. Maybe we can get useful content from this topic for everyone.

Useful contents will be appreciated

Thanks

How to call a set of shared named functions on different JavaScript objects based on the name of the current plugin clicked on

I am building a JavaScript app which will consist of multiple plugin apps and all data is fetched from a remote PHP API as JSON data.

The core app has a left sidebar which loads a list of Taxonomy items for the loaded plugin. For example the Bookmarks module loads a list of Tags in the sidebar. When a Tag is clicked on it then fetches a new list of Bookmark Entities from the API which belong to the clicked on Taxonomy tag record and then replaces the HTML list of tags with the new HTML list of Bookmark entities/records.

Clicking on a Bookmark entity record will then load the bookmark URL into a right iframe panel.

I plan to have several plugin apps in addition to the Bookmarks app and each plugin will load its own list of Taxonomy records and Entity records into the same HTML Sidebar element.

Each time a new list is generated it is simply injected into the DOM for the sidebar element replacing the previous old version.

SO I plan on having a separate JavaScript object/file for each module/plugin app and each app will have a set of functions which it has in common among all the apps.

For example something like loadSideBarTaxonomyList() function might be responsible for building the sidebar HTML for the current app plugin. So each plugin could have this same function and the core app could simply call this function for the currently loaded/selected plugin app.

This is where I am requesting your help and ideas.

If I have 10 plugin apps and 1 core app JavaScript. I might have a click event on a plugin selector widget which allows the user to select the plugin app to use.

In this click event I might want to fire off a call to the loadSideBarTaxonomyList() function on the selected plugin apps JavaScript object/code.

Keep in mind also that some of these plugin apps codebase will have its own set of click event handlers and such which all will might be watching or working on the same DOM elements at times. It might be useful to somehow un-load a module/plugin when a new one is clicked/selected to load?

So I am not sure how my code might look to handle calling a set of function names on the current selected plugin code?

Assume I have these plugin apps: - Bookmarks - Notebooks - Code Snippets

The user clicks to load the Notebooks app. I now need to call the function loadSideBarTaxonomyList() on the Notebooks app JavaScript. How might I call that function where the loaded app can change?

Is this a good use case for the Factory Pattern or possibly some other pattern fits best?

Also should I unbind each DOM event that a plugin app adds when a new plugin is loaded? So each time a plugin app is selected it will bind its own DOM events and when a new plugin is loaded it will first unbind the previous plugins DOM events. If I loaded the Bookmarks app 4 times within the hour, each time it would bind and unbind its events which I think might be a good idea?

Thanks for any help


enter image description here

Prototype pattern vs instantiation

what are advantages of using Prototype pattern over instantiation, except to reduce the overhead when creating objects that have heavyweight constructors

Is there a pattern in JavaScript for loosely coupled objects.

I'm relatively new to JavaScript so apologies if this type of question is an obvious one.

We have an app which uses etcd as its way to store data. What I'm trying to do is implement a way of swapping or alternating between different backend data stores (I'm wanting to use dynamodb).

I come from a C# background so if I was to implement this behaviour in an asp.net app I would use interfaces and dependancy injection.

The best solution I can think of is to have a factory which returns a data store object based upon some configuration setting. I know that TypeScript has interfaces but would prefer to stick to vanilla js if possible.

Any help would be appreciated. Thanks.

Using member variables in static function

I am having some issues with using a member variable within static function. I am trying to code a ramp up signal for stepper motor, that has to run on a arduino uno. The timer1 library available from arduino (http://ift.tt/2dg4Q8W), which interfaces with the timer1. The static function is a callback function which has to called everytime an interrupt occurs. When an interrrupt occurs, should the period time of the next pwm signal be decreased, and the amount it is decreased by is calculated within the interrupt/callback, and how I calulated is currently the problem.

The way i calulate is

uint32_t new_period = sqrt(2*n/4.8);
current_period -= new_period;

In which n should be increased for each completed period. I keep track of n by having it as a member variable inside of the class,

But that will not work, as the callback is a static function, and the variable is a member of the class.

I guess I could make it as a different design pattern - singleton, But there should be a different way to do the same thing, I would not like to use singleton in case of i would have to use multiple motors

Here is the .cpp

#include "stepper_motor.h"

int step_count = 0;
stepper_motor::stepper_motor()
{
  //pinMode(BUILTIN_LED,OUTPUT);
  pinMode(step_pin, OUTPUT);
  pinMode(dir_pin, OUTPUT);
  pinMode(en_pin, OUTPUT);
  alive_bool = true;
  position_bool = false;
  step_count = 0;
  period = 40825UL << 16; // 20412,5 us fixed point arithmetic time = 0

}

static void stepper_motor::callback()
{
  if (step_count < 240)
  {
    uint32_t new_period = sqrt(2 * step_count / 4.8);
    period -= new_period; 
  }
  else
  {
    return;
  }
}


void stepper_motor::step_pwm()
{

  digitalWrite(en_pin, HIGH);

  delay(0.005);

  digitalWrite(dir_pin, HIGH);
  //LOW  - Move towards the sensor
  //HIGH -  Move away from the sensor

  delay(0.005);

  int timestep = 0;

  timer1.initialize(period);
  timer1.attachInterrupt(callback);
}

and the .h file

#ifndef stepper_motor_h
#define stepper_motor_h

#include "Arduino.h"
#include <TimerOne.h>

#define step_pin  13
#define dir_pin   12
#define en_pin    11
#define max_step  200

 class stepper_motor
{
  public:
    stepper_motor();
    void step_pwm();
    static void callback();
    TimerOne timer1;
  private:
    uint32_t period;
    bool alive_bool;    
    //int step_count;
    bool position_bool;
};


#endif

jeudi 29 septembre 2016

Why do we use delegation in swift?

I'm trying to wrap my head around delegation. Put simply, my understanding is that one class delegates it's responsibilities to another class with a protocol definition handling the "contract" between the two. What is the point of this? Why not just have the delegating class handle it's own methods? Where can I read deeper about this concept?

Is this an example of a factory or strategy?

Suppose the following class chooses at runtime among a given set of instantiated singleton objects resolved from a dependency injection container:

class myClass {

    private container;   // DI container

    function getMeAnObject(input) {
        switch(input) {
            case A: return this.container.get(singletonA);
            case B: return this.container.get(singletonB);
            // etc...
        }   
    }
}

In this example would myClass be an implementation of the Factory or Strategy implementation or neither? Why?

Sample and hold patterns: period? (in Max/MSP)

I have two oscillators that produce 0 to 1 ramps at a given frequency. I am using a "sample and hold” (sah) function to get variable samples based on their varying frequencies. One oscillator is a trigger while the other is the sampled value. The sah works by outputting the value of the sampled ramp only when the trigger ramp crosses a certain threshold, say 0.5. So If the trigger has frequency 4Hz and the sampled oscillator has frequency 2Hz the sah will output 4 values per second, but the first couple of values is equal to the second couple since the two oscillators align halfway through. So far so good.

My problem is that I am trying to build an algorithm to calculate the period of the pattern given the two oscillators frequencies. In other words: how long will it take the pattern to start repeating? In the previous example it would be half a second. In particular I encounter problems when the two frequency values are not integers.

I worked with least common multiple function multiplying each value by 100 to get rid of the decimals and the dividing the result again by 100. It didn’t work. At this point I am very confused and could use an expert’s input.

Swift programming design pattern

I'm building a small app and got two views. Now I'm wondering whether I should build it in two ViewControllers or just use an UIView as overlay.

I have to deal with homescreen quick actions for both views. One opens the camera screen (view 01) and the other the timeline (view 02).

Should I use a transparent viewcontroller over the currentcontext of view 01 or just a regular UIView?

View 01 looks like this:

View 01

View 02 looks like this:

View 02

Design pattern for db operations on list of tables in java

I need suggestion on designing one of the use case. I have multiple classes which are responsible for inserting data into multiple tables i.e for example ClassA is responsible for inserting data into Table1, Table2, Table3 and ClassB is responsible for inserting into Table4, Table5 etc. So for each of the table I have a pojo class now. I have classes which has the logic to populate these pojo classes. So each class has to know the tables it is mapped to and call the respective class which populate and then persist them. How we effectively design this whole thing.

Decoupling a class which is used by the lots of subclasses

Hi I have a situation like that;

enter image description here

I have different items in my design and all these items has some specific effect on the Character. There is an apply function in every item so it can use Character object and change its functionalities. But what if I change the Character function, I would have to change all the Item classes in accordance to that.

How can I decouple Item and Character efficiently?

The language I am going to use is C++ and I don't know the other variables and functions inside the Item and Character classes. I just want to decouple them.

Which state machine design to use if your target state is not the next one?

I've been reading up on State Machines since its likely I need to use for my next project. Most examples I find online show how to go from StateA to StateB. But what if your next desired state is not an adjacent state? Are there any common patterns/practices to achieve this? Ideally in Java, but I can read other programming languages just as well.

# Example States
WakeUp->Get Dressed->Get Car Keys->Get in Car->Drive to Work->Work

Current State: Get in Car

Problems to solve

# Scenario 1: Desired State == Work
Forgot car keys, so you have to return to previous state and then move forward in states again.

# Scenario 2: Desired State == Work
Have car keys, so move forward in states to get to Desired State.

It's very likely that State Machine may not solve this problem elegantly and I just need to hand-craft the logic, I don't mind, but thought I'd follow a common design pattern to help others understand it.

From the example above, I do not need to worry about 'internal' states, which is also true for the project I'm tackling; just in case that makes a difference in possible solutions.

Module Pattern: var module = new function() {...} vs. var module = (function () {...}());

The Title is a very shorthand to the actual comparison I will give below. I'm delving into JavaScript and also read about the Module Pattern (JavaScript Module Pattern: In-Depth and Mastering the Module Pattern)

An implementation of my own of the Module Pattern was slightly different than the described pattern in the links above.

My implementation:

var smath1 = new function () {
        // "private fields"
        var answer = new Number(42);

        // "public fields"
        this.PI = new Number(3.141592653589793);

        // "private functions"
        function getHalfTheAnswer() {
                return answer / 2;
        };

        // "public functions"
        this.sum = function (a, b) { return new Number(a) + new Number(b) };
        this.mul = function (a, b) { return new Number(a) * new Number(b) };
        this.getTheAnswer = function () { return answer; };
        this.calcTheAnswer = function () { return getHalfTheAnswer() * 2 };
}

I'm interested in how this is different (technically/logically) from the Pattern described in the links...

var smath2 = (function () {

        var my = {};

        // "private fields"
        var answer = new Number(42);

        // "public fields"
        my.PI = new Number(3.141592653589793);

        // "private functions"
        function getHalfTheAnswer() {
                return answer / 2;
        };

        // "public functions"
        my.sum = function (a, b) { return new Number(a) + new Number(b) };
        my.mul = function (a, b) { return new Number(a) * new Number(b) };
        my.getTheAnswer = function () { return answer; };
        my.calcTheAnswer = function () { return getHalfTheAnswer() * 2 };

        return my;
}());

...and what makes the second approach superior/preferable to the first, if so at all?

The usage would be exactly the same as well as the behavior as far as I could see in my tests. See the fiddle: JS Module Pattern

Flask: How to use app context inside blueprints?

I'm learning flask and python and cannot wrap my head around the way a typical flask application needs to be structured.

I need to access the app config from inside blueprint. Something like this

#blueprint.py
from flask import Blueprint

sample_blueprint = Blueprint("sample", __name__)

# defining a route for this blueprint
@sample_blueprint.route("/")
def index():
     # !this is the problematic line
     # need to access some config from the app
     x = app.config["SOMETHING"]
     # how to access app inside blueprint?

If importing app in blueprint is the solution, will this not result in circulat imports? i.e importing blueprint in app, importing app in blueprints?

Detect and count numerical sequence in Python array

In a numerical sequence (e.g. one-dimensional array) I want to find different patterns of numbers and count each finding separately. However, the numbers can occur repeatedly but only the basic pattern is important.

# Example signal (1d array)
a = np.array([1,1,2,2,2,2,1,1,1,2,1,1,2,3,3,3,3,3,2,2,1,1,1])

# Search for the following patterns: [1,2,1], [1,2,3], [3,2,1] etc. ...

# Count the number of pattern occurrences
# [1,2,1] = 2 (occurs 2 times)
# [1,2,3] = 1 
# [3,2,1] = 1

I tried to solve the problem using np.where() without success. Thank you in advance for any suggestions!

What is the name of this design pattern using Performer?

What is the name of the pattern that used Retrofit 2.0 and some other libraries?

The old version

some manager can load data sync and async by two different methods

SomeClass obj = someManager.getDataSync();
SomeClass2 obj = otherManager.getBigDataSync()
SomeClass3 obj = otherManager2.getMyDataSync()

or

someManager.loadData(callback)
otherManager.loadData(callback2)
otherManager2.loadData(callbak3)

Now istead uses a helper class

New version

Performer<T> performer = someManager.getSomeData(...);

then we can execute this action sync or asyc with listener

T data = performer.performSync();

or

performer.performAsync(callback);

Redis Java Client: Do I need to buffer my commands into a pipeline for performance?

So I am just incrementing scores in a sorted set. That is the only command I am running, about 10-30 commands per second, from a Java application, using the Jedis client. Since I am just updating the scores, I don't care about the response either. My concern is that each 'zincrby' command is being put into its own packet and also of course waiting for the next reply before allowing my thread to resume (let's just assume there is a single thread doing all of this work).

So, I want to just implement pipe-lining to batch say 50 commands at at time. Here's where I see a code/design-pattern smell: Isn't this design pattern common enough that the driver should handle it? It appears that the .net "StackExchange.redis" driver does command batching automatically, but that the Java drivers don't have this feature? Is my idea to make a custom redis command buffer class, which puts incoming commands into a pipeline and calls sync() after 50 items, really needed?

Also, I noticed this in my logs, as I am using Jedis via Spring Data Redis:

20160929 06:48:27.393 [Twitter4J Async Dispatcher[0]] DEBUG o.s.d.r.c.RedisConnectionUtils # Closing Redis Connection
20160929 06:48:27.393 [Twitter4J Async Dispatcher[0]] DEBUG o.s.d.r.c.RedisConnectionUtils # Opening RedisConnection
20160929 06:48:27.393 [Twitter4J Async Dispatcher[0]] DEBUG o.s.d.r.c.RedisConnectionUtils # Closing Redis Connection
20160929 06:48:27.393 [Twitter4J Async Dispatcher[0]] DEBUG o.s.d.r.c.RedisConnectionUtils # Opening RedisConnection
20160929 06:48:27.393 [Twitter4J Async Dispatcher[0]] DEBUG o.s.d.r.c.RedisConnectionUtils # Closing Redis Connection
20160929 06:48:27.394 [Twitter4J Async Dispatcher[0]] DEBUG o.s.d.r.c.RedisConnectionUtils # Opening RedisConnection
20160929 06:48:27.394 [Twitter4J Async Dispatcher[0]] DEBUG o.s.d.r.c.RedisConnectionUtils # Closing Redis Connection
20160929 06:48:27.629 [Twitter4J Async Dispatcher[0]] DEBUG o.s.d.r.c.RedisConnectionUtils # Opening RedisConnection
20160929 06:48:27.630 [Twitter4J Async Dispatcher[0]] DEBUG o.s.d.r.c.RedisConnectionUtils # Closing Redis Connection
20160929 06:48:27.630 [Twitter4J Async Dispatcher[0]] DEBUG o.s.d.r.c.RedisConnectionUtils # Opening RedisConnection
20160929 06:48:27.631 [Twitter4J Async Dispatcher[0]] DEBUG o.s.d.r.c.RedisConnectionUtils # Closing Redis Connection
20160929 06:48:27.631 [Twitter4J Async Dispatcher[0]] DEBUG o.s.d.r.c.RedisConnectionUtils # Opening RedisConnection
20160929 06:48:27.631 [Twitter4J Async Dispatcher[0]] DEBUG o.s.d.r.c.RedisConnectionUtils # Closing Redis Connection
20160929 06:48:27.631 [Twitter4J Async Dispatcher[0]] DEBUG o.s.d.r.c.RedisConnectionUtils # Opening RedisConnection
20160929 06:48:27.631 [Twitter4J Async Dispatcher[0]] DEBUG o.s.d.r.c.RedisConnectionUtils # Closing Redis Connection
20160929 06:48:27.632 [Twitter4J Async Dispatcher[0]] DEBUG o.s.d.r.c.RedisConnectionUtils # Opening RedisConnection
20160929 06:48:27.632 [Twitter4J Async Dispatcher[0]] DEBUG o.s.d.r.c.RedisConnectionUtils # Closing Redis Connection
20160929 06:48:27.632 [Twitter4J Async Dispatcher[0]] DEBUG o.s.d.r.c.RedisConnectionUtils # Opening RedisConnection
20160929 06:48:27.632 [Twitter4J Async Dispatcher[0]] DEBUG o.s.d.r.c.RedisConnectionUtils # Closing Redis Connection
20160929 06:48:27.632 [Twitter4J Async Dispatcher[0]] DEBUG o.s.d.r.c.RedisConnectionUtils # Opening RedisConnection
20160929 06:48:27.633 [Twitter4J Async Dispatcher[0]] DEBUG o.s.d.r.c.RedisConnectionUtils # Closing Redis Connection
20160929 06:48:27.633 [Twitter4J Async Dispatcher[0]] DEBUG o.s.d.r.c.RedisConnectionUtils # Opening RedisConnection
20160929 06:48:27.633 [Twitter4J Async Dispatcher[0]] DEBUG o.s.d.r.c.RedisConnectionUtils # Closing Redis Connection
20160929 06:48:27.633 [Twitter4J Async Dispatcher[0]] DEBUG o.s.d.r.c.RedisConnectionUtils # Opening RedisConnection
20160929 06:48:27.633 [Twitter4J Async Dispatcher[0]] DEBUG o.s.d.r.c.RedisConnectionUtils # Closing Redis Connection

So it appears that it is closing the connection per naively executed command (via the Spring provided template pattern). I think that closing the connection forces the TCP buffer to send a single command per packet, so that seems pretty inefficient to me since sockets eats up a fair amount of CPU. Although the Spring Data Redis API does allow direct access to the Jedis client and won't close connections if a pipeline is currently open, so writing the "pipeline buffer" is an option with that.

In short, should I create/leverage a buffer that writes to a redis pipeline and the flushes after X commands? I simply don't like the idea of wasting all these CPU cycles (higher AWS bill) running each command naively, and am curious if there is a better design pattern for my scenario.

What is a good way to keep an in-memory change in sync with a backend

What is a good way to keep changes to a resource in sync with both in-memory and persistent storage in a multi-user situation? Here's two ideas, but they're both clumsy

Candidate A

Here, a copy of r must be retrieved so that in-memory state and persistent state is updated at the same time on put.

Resource r = resources.getDeepCopyOfResourceById("foo");
r.removeValue("bar");
resources.put(r);

Candidate B

Here, update operations are located on the service level. This appear to me as an object-oriented anti-pattern.

Resource r = resources.getResourceById("foo");
resources.removeValue("foo", r);

Is there a better way to design this?

Design pattern to handle different inputs working on the similar algorithm

So, this is pretty basic question but I thought I will see if someone could give a nice solution to it.

I have two similar implementations which work on different types of inputs and call same service but different APIs on the basis of the input and also perform some basic operations on the basis of the response of the previous call. I am looking for a better/logical/OOO way to represent this in java code.

public class C1 {

public O1 M1(I1 input) {

      callServiceXMethodA(input.a(), input.b()....)
      callServiceXMethodB(input.a(), input.b()....)
      callServiceYMethodA(input.a(), input.b()....)
      callServiceYMethodB(input.a(), input.b()....)
      extraStep1();

}

}

public class C2 {

public O2 M2(I2 input) {

     callServiceXMethodA(input.a(), input.b()....)
     callServiceXMethodSTU(input.a(), input.b()....)
     callServiceYMethodPQR(input.a(), input.b()....)
     callServiceYMethodB(input.a(), input.b()....)
     extraStep2();

}

}

I do see the a bit of template pattern (with some hierarchy on the input) or the visitor (though I am not too convinced given that there are only two input types).

I was thinking to keep an abstract class to put major chunk and keep abstract methods with whatever needs different values from the concrete implementation and entry point is the concrete class which routes the request with common parameters to the abstract class.

Can someone suggest a way to cleanly do this in OOO way?

R grep rows within a list

I have many data frame, so I import them as a list and I would like to grep the specific pattern in rows to create a data frame which contains only the specific pattern rows.

list
[1]
TBBA-06-5415-01A-01D-1481-05    g02726808   0.956810536587318   BSL
TBBA-06-5415-01A-01D-1481-05    g03242877   0.0365834311749085  BSL
TBBA-06-5415-01A-01D-1481-05    g06008330   0.0400302305964602  BSL
TBBA-06-5415-01A-01D-1481-05    g08861569   0.0556296569207048  BSL
TBBA-06-5415-01A-01D-1481-05    g09748749   0.183017407923698   BSL
[2]
TBBA-62-A472-01A-11D-A24I-05    g02726808   0.860054268107413   OTB
TBBA-62-A472-01A-11D-A24I-05    g04243127   0.897393495417269   OTB
TBBA-62-A472-01A-11D-A24I-05    g10537079   0.875143441641266   OTB
TBBA-62-A472-01A-11D-A24I-05    g12497728   0.935925242951832   OTB
TBBA-62-A472-01A-11D-A24I-05    g13195463   NA  OTB
[3]
TBBA-KK-A7AV-01A-11D-A32C-05    g02726808   0.862838460053133   AS
TBBA-KK-A7AV-01A-11D-A32C-05    g11045524   0.369049794350982   AS
TBBA-KK-A7AV-01A-11D-A32C-05    g13597397   0.235754213039205   AS
TBBA-KK-A7AV-01A-11D-A32C-05    g13835114   0.155860360642954   AS
TBBA-KK-A7AV-01A-11D-A32C-05    g14010829   0.668836842295365   AS
[N]
...

Desired output:
TBBA-06-5415-01A-01D-1481-05    g02726808   0.956810536587318   BSL
TBBA-62-A472-01A-11D-A24I-05    g02726808   0.860054268107413   OTB
TBBA-KK-A7AV-01A-11D-A32C-05    g02726808   0.862838460053133   AS
....

I would like to grep the second column the pattern g02726808 and grep each that row into a data frame. Thank you!

JavaFx how to avoid creating one huge controller

I have an app in JavaFX, which has main scene with menu and toolbar, and smaller scenes, which are injected into this main scene, after one of menu buttons are being pressed.

Now, HomeCntroller is responsible for either scene components: Home Scene (with toolbar and menu), and injected scene. This leads me to create massive, huge and very unprofessional controller if number of injected scenes is more than one.

How to split controller responsibility?

Now my Controller looks like this: changeDashboardPane method injects smaller Pane into my main HomePane.

@Component
@RequiredArgsConstructor(onConstructor = @__(@Autowired) )
public class HomeController extends AbstractController {
    private static final Logger LOG = Logger.getLogger(HomeController.class);

    private final BudgetProfileService budgetProfileService;

    @FXML
    private Label usernameLabel;

    @FXML
    private ComboBox<String> budgetProfilesComboBox; 

    @FXML
    private AnchorPane dashBoardPane;

    @FXML
    public void initialize() {
        refreshUsernameLabel();
        getAllBudgetProfiles();
        changeDashboardPane(PaneFactoryKeys.FINANCES_PANE);
    }

    private void refreshUsernameLabel() {
        String username = UserAccountProvider.getLoggedUser().getUsername();
        usernameLabel.setText(username);
    }

    private void getAllBudgetProfiles() {
        List<String> budgetProfileNames = budgetProfileService.getAllBudgetProfileNames();
        if (!budgetProfileNames.isEmpty()) {
            budgetProfilesComboBox.getItems().clear();
            budgetProfilesComboBox.getItems().addAll(budgetProfileNames);
        }
    }

    @FXML
    public void handleFinancesButtonAction() {
        changeDashboardPane(PaneFactoryKeys.FINANCES_PANE);
    }

    @FXML
    public void handlePeriodButtonAction() {
        changeDashboardPane(PaneFactoryKeys.PERIOD_PANE);
    }

    @FXML
    public void handleStatisticsButtonAction() {
        changeDashboardPane(PaneFactoryKeys.STATISTICS_PANE);
    }

    @FXML
    public void handleSettingsButtonAction() {
        changeDashboardPane(PaneFactoryKeys.SETTINGS_PANE);
    }

    private final void changeDashboardPane(String paneFactoryKey) {
        double injectedPanePosition = 0.0;
        Pane paneToChange = getPaneFromFactory(paneFactoryKey);
        dashBoardPane.getChildren().clear();
        AnchorPane.setTopAnchor(paneToChange, injectedPanePosition);
        dashBoardPane.getChildren().add(paneToChange);
    }

}

To get this more clear, screens:

without injected second pane with injected second pane

Any ideas guys?

Static ViewHolder Pattern. So whats the pattern for onClick inside this static Viewholder?

I know.

 public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener

static ViewHolder its recommended.

also onClick() in ViewHolder constructor its recommended instead of in onBind() method.

public ViewHolder(View v){
        super(v);
        v.setOnClickListener(this);
    }

but know we have inner onClick() in static ViewHolder class

  public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{

        public ViewHolder(View v){
            super(v);
            v.setOnClickListener(this);
        }

        @Override
        public void onClick(View v) {
            Log.d(TAG, "position = " + getAdapterPosition());
        }

and now is my question after all this recommendations.

Whats now its recommended if for example I want to delete item from list in this recycler and notifi adapter.

My list must be static OK.. But still can't use notifyDataSetChanged() in inner onClick();

any recommendations for this? pattern? or usefull example would be great. Or how You doing this in Your projects.

thx!

How to update two arguments at the same time using Ruby Observer method?

I am studying Ruby's Design Pattern and came across Observer method. I tried to customize my own observer method to help me understand it but it returns an error. Here is what I came up with:

class YummyTastyDonut
    def update(changed_order)
        puts "Kitchen: Yo, change the order to #{changed_order.order}!"
        puts "Front: Order for #{changed_order.name}!"
        puts "Front: The price will now be #{changed_order.order_price} "
    end
end


class Customer
    attr_reader :name, :order
    attr_accessor :order_price

    def initialize(name, order, order_price)
        @name = name
        @order = order
        @order_price = order_price
        @observers = []
    end

    def order=(new_order, new_price)
        @order = new_order
        @order_price = new_price
        notify_observers
    end

    def notify_observers
        @observers.each do |observer|
            observer.update(self)
        end
    end

    def add_observer(observer)
        @observers << observer
    end

    def delete_observer(observer)
        @observers.delete(observer)
    end
end

If you read the book, I changed the class names, but the essence is the same. One thing I changed is order= method; it now accepts two arguments instead of one.

The goal is, after creating new Customer, I want the new customer to be able to change my order and notify YummyTastyDonut. However, I want to be able to update two things: the order and order_price (obviously, if I change my order, the price will also change). I want YummyTastyDonut to respond to my change.

igg = Customer.new("Iggy", "Bacon Donut", 10)
=> #<Customer:0x0056212e48a940 @name="Iggy", @order="Bacon Donut", @order_price=10, @observers=[]>

donut = YummyTastyDonut.new
=> #<YummyTastyDonut:0x0056212e4894c8>

## Updating my order and order_price ##

   igg.order = ("yummy butter donut", 15)
#(repl):1: syntax error, unexpected ',', expecting ')'
#igg.order = ("yummy butter donut", 15)

If I use this order= method that accepts only one argument, it works just as expected.

def order=(new_order)
    @order = new_order
    notify_observers
end

 igg.order = "Triple bacon donut explosion"
Kitchen: Yo, change the order to Triple bacon donut explosion!
Front: Order for Iggy!
Front: The price will now be 10 

What do I have to change so I can update both order and order_price simultaneously?

Is this an example of the Functional Decomposition AntiPattern, Strategy pattern or something else entirely?

For one of my Android projects I have created a framework (for lack of a better word) of interacting with my SQLiteDatabase in the following manner. However, I recently came across an acticle explaining the Functional Decomposition AntiPattern in the Object Oriented paradigm. This article mentioned tell-tale signs of this AntiPattern are classes with the names of a function and classes with only one or two methods. My framework exhibits both of these tell-tale signs.

I find the code works quite well as it provides a blueprint for creating new queries, removes the chances of forgetting to close a connection or cursor and enables easy reuse of boilerplate code. So if this is in fact an anti-pattern, I would have to reconsider the way I design software, as I use the same construct for communicating with my webserver (a framework built around AbstractHttpRequest, AbstractGet and AbstractPost classes).

The following example shows how this framework would go about blueprinting get and update requests to the database. Please keep in mind that these code snippets are heavily simplified for the sake of easy understanding.

A database query would then be executed by calling, for example:

UserEntity user = new GetUserById(12).submit();

My question is this: is the following code an example of the Functional Decomposition AntiPattern, the Strategy Pattern or something else entirely? If it is something else entirely, would you consider this good code or bad?

Class Diagram

class diagram

AbstractDatabaseQuery

public class AbstractDatabaseQuery<T>
{
    private DatabaseMode mDatabaseMode;

    public AbstractDatabaseQuery(DatabaseMode mode) 
    {     this.mDatabaseMode = mode;}

    public abstract T perform(SQLiteDatabase database);

    public T submit() 
    {
         //Get readable or writeable database depending on the mode.
         SQLiteDatabase database = this.mDatabaseMode.getDatabase();

         //Perform the query.
         T result = perform(database);

         //Close the connection.
         this.mDatabaseMode.close(database);

         //Return the result.
         return result;
    }
}

AbstractGet

public class AbstractGet<T extends AbstractDatabaseEntity> extends AbstractDatabaseQuery<T>
{
    public abstract String getQuery( )
    public abstract String[ ] getQueryParameters( )
    public abstract T getResultFrom(Cusor cursor)

    public AbstractGet( ) 
    {     super(DatabaseMode.Read);}

    @Override
    public T perform(SQLiteDatabase database)
    {
         //Perform the query.
         Cursor cursor = database.rawQuery(getQuery( ), getQueryParameters( ));

         //Defer getting the query result to the concrete implementation of the class.
         T result = getResultFrom(cursor);

         //Close the cursor.
         cursor.close();

         //Return the result.
         return result;
    }   
}

AbstractUpdate

    public class AbstractUpdate<T extends AbstractDatabaseEntity> extends AbstractDatabaseQuery<Integer>
    {
        public abstract AbstractDatabaseTable getTable();
        public abstract ContentValues insertUpdates(ContentValues cv, AbstractDatabaseTable table);
        public abstract String getWhereClause( );
        public abstract String getWhereArguments( );

        private T mEntity;

        public AbstractUpdate(T entity)
        {    
             super(DatabaseMode.Write);  
             this.mEntity = entity;
        }

        @Override
        public Integer perform(SQLiteDatabase database)
        {
             //Get the table object, which contains (amongst others) the table name and its columns.
             AbstractDatabaseTable table = getTable();

             //Create the object holding the new values.
             ContentValues cv = new ContentValues();

             //Add default values such as the last time-of-editing.
             if(table.hasEditedColumn())
             {     cv.put(AbstractDatabaseTable.KEY_EDITED, System.currentTimeMillis());}

             //Defer adding the rest of the new values to the concrete implementation of the class.
             cv = insertUpdates(cv, table);

             //Safe-guard for the concrete implementation of the class returning null instead of cv.
             if(cv == null)
             {     throw new IllegalStateException("ContentValues cv is null. Please make sure you return cv from insertUpdates(cv, table)");}

             //Perform the operation and return the amount of rows affected.
             int rowsAffected = database.update(table.getName( ), cv, getWhereClause( ), getWhereArguments( ));
             return rowsAffected;
        }
    }

GetUserById

public class GetUserById extends AbstractGet<UserEntity>
{
      private long mUserId;

      public GetUserById(long userId)
      {
           super();
           this.mUserId = userId;
      }

      @Override
      public String getQuery( )
      {     
            DatabaseManager dm = DatabaseManager.getInstance();
            AbstractDatabaseTable users = dm.getTableById(R.id.database_table_users);

            return "SELECT * FROM " + users + " WHERE _id = ?";
      }

      @Override
      public String[ ] getQueryParameters( ) 
      {     return new String[ ] {String.valueOf(this.mUserId)};}

      @Override
      public UserEntity getResultFrom(Cursor cursor) 
      {     return new UserEntity(cursor);}
}

GetAllUsers

public class GetAllUsers extends AbstractGet<ArrayList<UserEntity>>
{
    @Override
    public String getQuery()
    {     return "SELECT * FROM User";}

    @Override
    public String[ ] getQueryParameters( ) 
    {     return null;}

    @Override
    public UserEntity getResultFrom(Cursor cursor) 
    {     
         ArrayList<UserEntity> users = new ArrayList();

         for(cursor.moveToFirst() ;  ! cursor.isAfterLast() ; cursor.moveToNext())
         {     users.add(new UserEntity(cursor));}

         return users;
    }
}

UpdateUser

public class UpdateUser extends AbstractUpdate<UserEntity>
{
    public UpdateUser(UserEntity userEntity)
    {     super(userEntity);}

    @Override
    public AbstractDatabaseTable getTable()
    {     return DatabaseManager.getInstance().getTableById(R.id.database_table_users);}

    @Override
    public ContentValues insertUpdates(ContentValues cv, AbstractDatabaseTable table)
    {
         AbstractDatabaseColumn columnFirstName = table.getColumnById(R.database_column_user_first_name);
         cv.put(columnFirstName.getName(), this.mEntity.getFirstName());

         AbstractDatabaseColumn columnLastName = table.getColumnById(R.database_column_user_last_name);
         output(columnLastName.getName(), this.mEntity.getLastName());

         return cv;
    }

    @Override 
    public String getWhereClause()
    {     return AbstractDatabaseTable.KEY_ID + " = ?";}

    @Override
    public String[] getWhereArguments()
    {     return new String[ ] {String.valueOf(this.mEntity.getDatabaseId())};}
}

suggest best design pattern

I have assigned a code refactoring task of a screen. My app written in spring mvc. Screen consists of 5 sections my goals, group goals, department goals, organization goals and peer goals. Each section has own data table and dropdowns to render data table on different condition. Few of them bind from 1 controller where as few have other controllers to render data.

I need suggestion how to clean code will all section has its own controller or there should b onee controller to entertain all request. And which design pattern is most appropriate to solve this problem.

Where to put business logic when using entity with MVP pattern

I have entities that are very dumb and only holds the data. I used to put some business logic inside the entities or presenter, i.e.

  • Movie.findMostWatchedTopTenMovies
  • Movie.hasWatchedThisMovie
  • TheatrePresenter.canScreenMoreMovies

(assume that these method contains some complex logic and it's not just getter)

but this seems against the SOLID principle and it's not test friendly code. So where is the most appropriate place to put this logic? And what should the class name be?

Is there some desing pattern or guide line to use two Finite State Machines in the same system, and both interact between them?

In my system there are external signals than affect one state machine, this implies that the other FSM change his state because of this, so the system seems to me not scalable. What would be the best solution to this?

What is the best approach for working with too many large images in three layer architecture c# [on hold]

I have a project with Three Layer Architecture in C# .NET :

  1. MVC Application (Presentiation Tier): is the tier in which users interact with an application
  2. Web Service (Middle Tier): is the layer that the presentation tier and the data tier use to communicate with each other.

  3. Sql Database (Data Tier): is basically the server that stores the MVC application data.

Three Layer Architecture

Now I need to store many large photos that uploaded from presentation. Sending these files to the web service failed beacuas it exceed the default maximum upload file size in IIS (4MB).

Therefore I have some possible solution for sending large file. And some approach for storing and retrieving it.

Sending:

  1. Don't send images to the Data Layer and store them in the presentation server : this maybe hit in performance of Presentation Server.
  2. Increase maximum upload file size in web config and send them as http post requests.
  3. Using SOAP messages with attachments.
  4. Using File transfer (ftp)

Storing and Retrieving:

  1. Using SQL FileStream or FileTable and storing files in separate database.
  2. Using file system and saving images as files: I think this is easier than storing in SQL to support and maintenance.
  3. Using a FTP server (related to file transfer).

Consider to support and maintenance, when number of the images pass a million; what is the best approach?

Design Pattern or Design for A workflow that has multiple inputs

What will be a good design or design pattern for a workflow like this. Due to time constraints I had to quickly code a workflow as seen below a few months ago. Now I am looking at refactoring it.

            SwfEventInitOutput swfEventInitOutput = EventInit(request);

            SwfAuthorisationOutput swfAuthorisationOutput = Authorisation(request, swfEventInitOutput);

            if (swfAuthorisationOutput.getResultCode() != CommonResult.SUCCESS.getResultCode()) {
                return processCCExceptionResponse(request, swfAuthorisationOutput.getResultCode(), null, false, null, swfEventInitOutput, swfAuthorisationOutput, null);
            }

            SwfLocationDetectionOutput swfLocationDetectionOutput = LocationDetection(request, swfEventInitOutput, swfAuthorisationOutput);
            if (swfLocationDetectionOutput.getResultCode() != null && swfLocationDetectionOutput.getResultCode() != 0) {
                return processCCExceptionResponse(request, swfLocationDetectionOutput.getResultCode(), null, false, null, swfEventInitOutput, swfAuthorisationOutput, swfLocationDetectionOutput);
            }





.....

   // here it prepares the input to the flow and returns the output 
   private SwfEventInitOutput EventInit(ProcessCCRequest request) {
        SwfEventInitInput eventInitInput = new SwfEventInitInput();
        eventInitInput.setTransactionId(request.getTransactionId());
        eventInitInput.setNetworkEvent(request.getNetworkEvent());
        eventInitInput.setSubscriberId(request.getSubscriberId());

        SwfEventInit eventInit = gyWorkflowFactory.getSwfEventInit();
        SwfEventInitOutput swfEventInitOutput = eventInit.execute(eventInitInput);

        return swfEventInitOutput;

    }

1) Some workflows need more than an output from two different flows for example SwfLocationDetection , or more (not shown above)

2) The chain is something like this

  • if successful (resultCode == 0) EventInit->Authorisation->LocationDetection->FlowX->FlowZ->CcaDp

and if failure(i.e resultCode !=0)

  • failure at Authorisation: EventInit->Authorisation->CcaDp
  • failure at LocationDetection:
    EventInit->Authorisation->LocationDetection->CcaDp

3) here are interfaces

public interface SwfInput {

}


public interface SwfOutput {
    Long resultCode;
}

so for example

public SwfEventInitOutput implements SwfOutput {
    Long resultCode;

}

public SwfEventInitInput implements SwfInput {

}




public interface GyWorkflow<I extends SwfInput, O extends SwfOutput> {

    public O execute(I input);

}
so 


public class SwfEventInit extends AbstractWorkflow<SwfEventInitInput, SwfEventInitOutput> {
     public SwfEventInitOutput execute (SwfEventInitInput input) {
}

Java Logical pattern [on hold]

In this image given Have to use some simple logic to produce same kind of Logic. Can anybody help me out Thanks in advance

1

How to declare friend classes while using decorator and iterator design patterns

I have created a ListAsDLL class (doubly linked list) by decorating a ListAsSLL class (singly linked list). Now I would like to incorporate an Iterator class to cycle through the ListAsDLL class. My code is as follows:

#include <iostream>
using namespace std;

class ListAsSLL
{
protected:
    struct node{
        int i;
        struct node* next;
    };
    node* head;
    node* tail;
    int listSize;

public:
    ListAsSLL()
    {
        head = 0;
        tail = 0;
        listSize = 0;
    }
    virtual void addToBeginning(int i)
    {
        node * temp = new node;
        temp->i = i;
        if(head==0){
            temp->next = 0;
            tail = temp;
        }else if(head == tail) {
            temp->next = tail;
        }
        else{
            temp->next = head;
        }
        head = temp;
        listSize++;
    }
    virtual void print()
    {
        node* temp = head;
        for (int i = 0; i < listSize; ++i) {
            cout<<temp->i<<" "<<endl;
            temp = temp->next;
        }
    }
};

class Decorator : public ListAsSLL
{
private:
    ListAsSLL* list;
public:
    Decorator(ListAsSLL* l)
    {
        list = l;
    }
    virtual void addToBeginning(int i)
    {
        list->addToBeginning(i);
    }
    virtual void print()
    {
        list->print();
    }
};

class PreviousDecorator : public Decorator
{
protected:
    struct dnode : public node
    {
        node* prev;
    };
    dnode* head;
    dnode* tail;
    int listSize;

public:
    PreviousDecorator(ListAsSLL* l) : Decorator(l)
    {
        listSize = 0;
        head = 0;
        tail = 0;
    }
    virtual void addToBeginning(int i)
    {
        Decorator::addToBeginning(i);
        dnode * temp = new dnode;
        temp->i = i;
        if(head==0){
            temp->next = 0;
            tail = temp;
        }else if(head == tail) {
            temp->next = tail;
            tail->prev = temp;
        }
        else{
            temp->next = head;
            tail->prev = temp;
        }
        temp->prev = 0;
        head = temp;
        listSize++;
    }
    virtual void print()
    {
        Decorator::print();
        node* temp = head;
        for (int i = 0; i < listSize; ++i) {
            cout<<temp->i<<" "<<endl;
            temp = temp->next;
        }
    }
    friend class DLLIterator;
};

class ListAsDLL : public ListAsSLL
{
public:
    virtual void addToBeginning(int i){}
    virtual void print(){}
};

class DLLIterator
{
private:
    ListAsDLL* dll;
public:
    DLLIterator(ListAsDLL* dll)
    {
        this->dll = dll;
    }
    int getFirst()
    {
        return dll->head->i;
    }
};

int main() {
    ListAsSLL* dll = new PreviousDecorator(new ListAsDLL());
    dll->addToBeginning(20);
    DLLIterator* it = new DLLIterator((ListAsDLL*) dll);
    cout<<it->getFirst()<<endl;

    delete dll;
    delete it;
    return 0;
}

The only problem is that because I am passing in a ListAsDLL as a parameter to the Iterator class I am unable to access the protected attributes of the class it is being decorated with. Therefore I cannot access dll->head->i.

Firstly, am I using the decorator design pattern correctly? And secondly how can I access the protected attributes of a class that a friend class has been decorated with.

How to use builder pattern with Spring annotation

I would like to eliminate too many of "new" creation in my code. So I decided to use builder pattern. I also would like to take advantage of Spring @Autowired if possible.

public class Car
{
    @Autowired
    private Radio radio;

    @Autowired
    private Speaker speaker;

    @Autowired
    private Engine engine;

    private String model;

    public Car createCar()
    {
        radio.add(speaker);
        return this;
    }

    public static class Builder
    {
        private String model;

        public Builder(){}

        public Builder model(String model)
        {
            this.model = model;
            return this;
        }
    }
}

I would like to use perhaps something like this.

Car car = new Car.Builder().model("A123").build();

Would this be possible to do?

Generating C# form controls dynamically with abstract factory pattern

I am trying to create a form application with customizable "themes" using the abstract factory pattern (just to get some experience with it). I have created an implementation of a theme-factory like this:

public class BlueTheme : IThemeFactory
{
    public Button CreateButton() => new BlueButton();
    // ... more controls here ...
}

Now I pass an IThemeFactory instance through the constructor of my Form:

private IThemeFactory _themeFactory;

public Form1(IThemeFactory theme)
{
    _themeFactory = theme; // e.g. new BlueTheme()
    InitializeComponent();
}

My question is: Are there ways make my form use the IThemeFactory.CreateButton() method to generate all of the buttons on the form?

Using decorator design pattern to create a doubly linked list by decorating a singly linked list

I am quite a newbie when it comes to design patterns so am having a hard time grasping the concept of the decorator design pattern. Is it possible to decorate a singly linked list class to a doubly linked list class which inherits from it? I would like to decorate the following class:

ListAsSLL.h:

#ifndef LISTASSLL_H
#define LISTASSLL_H

class ListAsSLL
{
protected:
    struct node{
        int i;
        struct node* next;
    };
    node* head;
    node* tail;
    int listSize;

public:
    ListAsSLL();
    virtual void addToBeginning(int obj);
    virtual void addAtPos(int obj, int i);
    virtual void addToEnd(int obj);
    virtual void del(int i);
    virtual void overwrite(int obj, int i);
    virtual void grow();
    virtual void shrink();
};

#endif //LISTASSLL_H

Giving the doubly linked list class the same functionality with the added feature of having a struct with a pointer to the previous node.

Hopefully someone can shed some light on how to do this. Thanks in advance.

Build an object having nested entities.Design Pattern

I am using Java 1.6

Scenario: I have an entity structure called 'pnr' which looks like this:

<pnr>
    <outbound>
        <travellers>
            <person>
                <name></name>
                <address></address>
            </person>
            <person>
                <name></name>
                <address></address>
            </person>
        </travellers>
        <segments>
            <segment>
                <from></from>
                <to></to>
                <date></date>
                <flight-details>
                    <flight-id></flight-id>
                </flight-details>
            </segment>

            <segment>
                <from></from>
                <to></to>
                <date></date>
                <flight-details>
                    <flight-id></flight-id>
                </flight-details>
            </segment>
        </segments>
    </outbound>

    <inbound>
        ...
    </inbound>
</pnr>

I want to build an object whose structure looks like the above XML. I start with an object of class "Pnr" which looks like this:

class Pnr{
    Outbound outbound;
    Inbound inbound;
}

//Outbound
class Outbound{
    ...
}

//Inbound
class Inbound{
    ...
}

The nesting of entities follows and each entity is represented by a class.

Please suggest a design pattern to build the nested Pnr object.

I have gone through the builder pattern. But in my case: 1) We dont have too many parameters which we are passing to any of the constructors. 2) All the time we want the whole Pnr object to be built. So we dont require a number of constructors with different parameter list.

But I have to handle building of the nested entities effectively. Should I still go with builder pattern ?

If not please suggest which design pattern will be suitable for such a case.

Thank you!

Builder Pattern more than one director

I want to know if a Builder Pattern can have more than one Director? Because I have to build a object that have different implementations.

For example,

Sometime the object is constructed from slugs so I have to use a foreach to add different slugs to object.

//Director 1

function build ($obj) {
    foreach($slugs as $slug) {
        $object = $obj->createObject($slug);
        $object->buildItem1();
        $object->buildItem2();
    }
}

But, other times the object is built out every lines.

//Director 2

function build ($obj) {
    $object = $obj->createObject();
    $object->buildItem1();
    $object->buildItem2();
}

Difference between MVVM and MVA (Model-View-Adapter)

What is the difference between MVVM and MVA (Model-View-Adapter)?

As long as in both patterns:

  1. The VM and Adapter mediate between View and Model.
  2. There could be more than one VM and Adapter participated in these patters for the same model.
  3. The model interacts directly with VM and Adapter.

The only thing that comes to my mind is that in MVVM, VM will not receive any notifications from Model, but in MVA the adapter receives notifications from Model!

So how the difference of these patterns can be explained?

Why to use Builder Pattern instead of using methods return self-instance of the class (factory method)

What is the difference to use this approach to standard way of creating Builder Pattern within the class:

public class MyClass {
private String name;
private String address;
private String email;

public MyClass(){}

public MyClass withName(String name) {
 this.name = name; 
 return this;
}
public MyClass withAddress(String address) {..}
public MyClass withEmail(String email) {..}

}

MyClass clazz = new MyClass().withAddress("").withName("").withEmail(""); Effect is the same. What I've missed?

Really What is Module definition? [on hold]

I've worked with different php frameworks, and realized that most of them have something called module. but as you know implementation of module in each framework differs from others. currently I'm working on Yii2 and realized that it has one of best modules implementation I've ever seen.

but yet I don't know is there any obvious definition for module ?? now when you tell me module I think of

bunch of code which tries to be independent from other parts of software and it contains different types of codes . like views, controller actions , models , migrations , seeders , ...

but I faced multiple situations which one module has a small bit of dependency to other module. for example if you have user module it is highly possible that the other modules are dependent to this this module. this dependency could be any thing. maybe in your comment module your "comment model" users "user model"

or maybe in one of your modules you have a service or component (yii style) that you want call from other modules.

all of these are samples of dependency and I'm sure there are more of them.

but what I want to know from your experiences is what is the best way to create a modular software in a way which modules have the minimum amount of dependency to each other and modules are reusable and so software is really extendable?

I myself think in php traits really help to have more independent code in our modules.

Sort of multiple inheritance?

I have the following class structure (Blah === ExtBlah):

Base
 +--[ ExtBase ]    --???-- [ ExtBlah ] --- .. more scripts ...
 +--[ Blah ]
        +---[ Script1 ]
        +---[ Script2 ]
        +---[ ....... ]
        +---[ ScriptN ]     

Now I need to write more Scripts which need to extend Blah, but Blah has to extend "ExtBase", instead of "Base" for the new script cases.

I still have to have Blah the way it is because the Scripts1-N have to be dependent on "Base", not on "ExtBase".

Also I don't want to create a copy of Blah i.e. ExtBlah, because that mean duplication of code and will be harder and messier to support.

Any ideas ?

Notify nurse about the frequency of a medicine the patient must take

When you get a prescription from a pharmacy, there is a start date associated with the medication. Medications also have a scheduled frequency that tells you when to take the doses. There are fairly common patterns for the frequencies. You can take them every 4 hours. You can take them once a day. You can take them with meals or just before bed. You can also take them PRN or "as needed." Many medications also have a stop. You may need to take the medication for 7 days. You may need to take a certain number of doses. You may also take the medication for the rest of your life. Assume you have to implement a system to tell nurses when a patient should receive medications. How would you model a schedule for a medication that handles start dates, end dates, and frequencies?

I have done basic design ..but I'm stuck with implementing the schedule functionality (notification functionality that notifies the nurse bout medicine frequency )

The solution i have is

Frequency Class

    package patientmedicine;

public class Frequency {

public PartoftheDay part;
public enum PartoftheDay
{
    Morning,
    Afternoon,
    Evening,
    Night
}

public Frequency( PartoftheDay part ) {
    this.part = part;

} 

public PartoftheDay getPart() {
    return part;
}
public void setPart(PartoftheDay part) {
    this.part = part;
}

}

Medicine Class

    package patientmedicine;

import java.util.List;

public class Medicine {

private String name;
private String disease;
private String composition;
private String details;
private List<Frequency> frequencyList;



public List<Frequency> getFrequencyList() {
    return frequencyList;
}

public void setFrequencyList(List<Frequency> frequencyList) {
    this.frequencyList = frequencyList;
}

public String getName() {
    return name;
}

public Medicine(String name, String composition, String details) {
    this.name = name;
    this.setComposition(composition);
    this.setDetails(details);

}

public void setName(String name) {
    this.name = name;
}
public String getDisease() {
    return disease;
}
public void setDisease(String disease) {
    this.disease = disease;
}

/**
 * @return the composition
 */
public String getComposition() {
    return composition;
}

/**
 * @param composition the composition to set
 */
public void setComposition(String composition) {
    this.composition = composition;
}

/**
 * @return the details
 */
public String getDetails() {
    return details;
}

/**
 * @param details the details to set
 */
public void setDetails(String details) {
    this.details = details;
}

}

Patient class

    package patientmedicine;

import java.util.List;

public class Patient {

private String name;
private String disease;
private List<Medicine> medicineList;



public Patient(String name, String disease) {
    this.setName(name);
    this.setDisease(disease);

}



public List<Medicine> getMedicineList() {
    return medicineList;
}



public void setMedicineList(List<Medicine> medicineList) {
    this.medicineList = medicineList;
}



/**
 * @return the name
 */
public String getName() {
    return name;
}

/**
 * @param name the name to set
 */
public void setName(String name) {
    this.name = name;
}

/**
 * @return the disease
 */
public String getDisease() {
    return disease;
}

/**
 * @param disease the disease to set
 */
public void setDisease(String disease) {
    this.disease = disease;
}

}

Program Class

    package patientmedicine;

import java.util.ArrayList; import java.util.List;

import patientmedicine.Frequency.PartoftheDay;

public class Program { // private List patientList;

public static void main(String[] args) {

    List<Frequency> freque1 = new ArrayList<Frequency>();
    freque1.add(new Frequency(PartoftheDay.Morning));
    freque1.add(new Frequency(PartoftheDay.Evening));

    // List<Medicine> medicine = new ArrayList<Medicine>();
    Medicine med1 = new Medicine("Paracetemol", "38g", "For fever");
    med1.setFrequencyList(freque1);

    List<Frequency> freque2 = new ArrayList<Frequency>();
    freque2.add(new Frequency(PartoftheDay.Morning));
    freque2.add(new Frequency(PartoftheDay.Evening));

    Medicine med2 = new Medicine("Ibuprofen", "38g", "For body pains");
    med2.setFrequencyList(freque2);

    List<Medicine> medicineList = new ArrayList<Medicine>();
    medicineList.add(med1);
    medicineList.add(med2);

    Patient patient1 = new Patient("Deepthi", "For body pains");
    patient1.setMedicineList(medicineList);

    List<Patient> patientList = new ArrayList<Patient>();
    patientList.add(patient1);

    for (Patient patientt : patientList) {
        System.out.println(patientt.getDisease());
        System.out.println(patientt.getName());

        for (Medicine medi : patientt.getMedicineList()) {

            System.out.println(medi.getDetails() + medi.getComposition()
                    + medi.getName());

            for (Frequency freq : medi.getFrequencyList()) {
                System.out.println(freq.getPart());
            }

        }

    }

}

}

Keeping builder in seperate class (fluent interface)

Foo foo = Foo.builder()
    .setColor(red)
    .setName("Fred")
    .setSize(42)
    .build();

So I know there is the following "Builder" solution for creating named parameters when calling a method. Although, this only seems to work with inner static classes as the builder or am I wrong? I had a look at some tutorials for builder pattern but they seem really complex for what im trying to do. Is there any way to keep the Foo class and Builder class seperate while having the benefit of named parameters like the code above?

Below a typical setup:

   public class Foo {
      public static class Builder {
        public Foo build() {
          return new Foo(this);
        }

        public Builder setSize(int size) {
          this.size = size;
          return this;
        }

        public Builder setColor(Color color) {
          this.color = color;
          return this;
        }

        public Builder setName(String name) {
          this.name = name;
          return this;
        }

        // you can set defaults for these here
        private int size;
        private Color color;
        private String name;
      }

      public static Builder builder() {
          return new Builder();
      }

      private Foo(Builder builder) {
        size = builder.size;
        color = builder.color;
        name = builder.name;
      }

      private final int size;
      private final Color color;
      private final String name;
    }

What is the correct approach towards Factory Pattern?

I have been reading a lot of stuff regarding Factory Pattern approach and in all of them there seems to be a static method in the factory which based on switch-case returns the desired product at run-time, but this seems to violate Open Close principle as every time there is a new product the factory class needs to be modified to make necessary changes.

Below is a code i think also is in line with factory pattern but i am not sure if this approach is correct. basically what i think is that the client will know what type of factory it needs, based on that it case get the product that factory alone handles,

Please let me know if this is the right approach, or if there is a better one.

#include "iostream"
#include "memory"
using namespace std;

class AbstractDog{
    public:
        virtual void bark(void) = 0;
        AbstractDog(){cout << "AbstractDog created"<<'\n';}
        virtual ~AbstractDog(){cout << "AbstractDog destroyed"<<'\n';}
};

class chiwawa : public AbstractDog{
    public:
        void bark(void){
            cout << "bark like chiwawa"<<'\n';
        }
        chiwawa(){cout << "chiwawa created"<<'\n';}
        virtual ~chiwawa(){cout << "chiwawa destroyed"<<'\n';}
};

class alsatian : public AbstractDog{
    public:
        void bark(void){
            cout << "bark like alsatian"<<'\n';
        }
        alsatian(){cout << "alsatian created"<<'\n';}
        virtual ~alsatian(){cout << "alsatian destroyed"<<'\n';}
};


class AbstractDogFactory{
    public:
        virtual AbstractDog* getDog(void) = 0;
        AbstractDogFactory(){cout << "AbstractDogFactory created"<<'\n';}
        virtual ~AbstractDogFactory(){cout << "AbstractDogFactory destroyed"<<'\n';}
};

class smallDogFactory : public AbstractDogFactory{
    public:
        virtual AbstractDog* getDog(void){
            return new chiwawa;
        }
        smallDogFactory(){cout << "smallDogFactory created"<<'\n';}
        virtual ~smallDogFactory(){cout << "smallDogFactory destroyed"<<'\n';}
};

class bigDogFactory : public AbstractDogFactory{
    public:
        virtual AbstractDog* getDog(void){
            return new alsatian;
        }
        bigDogFactory(){cout << "bigDogFactory created"<<'\n';}
        virtual ~bigDogFactory(){cout << "bigDogFactory destroyed"<<'\n';}
};


int main() {
    auto_ptr<AbstractDogFactory> m_ptr_fact(new bigDogFactory);
    auto_ptr<AbstractDog>        m_ptr_dog(m_ptr_fact->getDog());
    m_ptr_dog->bark();
    return 0;
}

spring aop follows proxy design pattern OR interceptor design pattern [on hold]

Can any one help me in understanding Proxy design pattern and interceptor design pattern.

Why Sprig AOP uses proxy design pattern instead interceptor design pattern

lundi 26 septembre 2016

What are the drawbacks of Singleton Design Pattern?

What are the drawback of Singleton Design pattern? Is it memory allocation or anything else??

Provide support of different resolution for mobile and tablet?

I want to develop application which should support android mobile resolution as well as tablet resolution.

Q1) What is different between density and resolution?

Q2) Designer generally design application in pixel (1440x2560) how designer will take care of density what should he have to take care at time of design?

Q3) What is the best way to handle font size for different resolution/density?

Q3) Which drawable folder is represent which device resolution/density?

Q4) Application Launcher icon size for different resolution/density?

Q5) Notification icon/Statusbar icon size for different resolution/density?

dimanche 25 septembre 2016

Alternative for If conditions and replacing it with inheritance

So my problem is that you have a lot of if conditions to be checked and inside that if condition you have multiple lines of code. I want to eliminate it and use inheritance instead. For every if statement I will be using a separate class to handle it. This is more like a derivative of the command pattern but not command pattern itself.

I have an interface which contains only one method which defines the task i want it to be implemented. I have an abstract class implementing that interface and contains a static map and static methods to add values and retrieves the task. The classes i specified will be extending this Handler class.

This is my scenario.

I am sending a string as parameter to get a specific translator. Let's say sinhala or tamil or english. On each implementation of those translators, I will be adding the necessary values to the map in the Handler class in a static block. Basically adding them in the class load time.

Below is my code.

Command Interface

public interface Command {
    LanguageTranslator getLangTranslator();
}

Handler Abstract class

public abstract class Handler implements Command {

    private static Map<String, Command> map = new HashMap<>();


    public static void AddToMap(String key, Command command){

        map.put(key,command);
    }
    public static LanguageTranslator getTranslator(String value) throws Exception {
        if (!(map.containsKey(value))){
            throw new LanguageNotFoundException("Translator not found");
        }else {
            return map.get(value).getLangTranslator();
        }
    }


}

Sinhala Translator

public class SiCommand extends Handler {
    static {
        Handler.AddToMap("1",new SiCommand());
    }

    @Override
    public LanguageTranslator getLangTranslator() {
        return new SiTranslator();
    }

}

Tamil Translator

public class TiCommand extends Handler {
    static {
        Handler.AddToMap("2",new TiCommand());
    }

    @Override
    public LanguageTranslator getLangTranslator() {
        return new TiTranslator();
    }

}

English Translator

public class EnCommand extends Handler {
    static {
        Handler.AddToMap("3",new EnCommand());
    }

@Override
    public LanguageTranslator getLangTranslator() {
        return new EnTranslator();
    }

}

Demo

 RowTranslator rowTranslator = Handler.getTranslator("2");

Questions

Since All values are assigned to the map during the class loadding time these are my questions

  1. Is using static blocks like this a good practice ?

  2. I want to eliminate the use of if conditions as i mentioned before. By using this method when ever someone wants to add a new if condition, you just only have to create a new class extending handler and implement it. Therefore the outside user doesn't need to know the internal handling of the Command's sub classes. The output is just gonna be a translator. Is this a good way of doing it? What are the better alternatives? What should be adjusted?

Note

Also I will be focusing strictly on Open/Close principle as well

decorator pattern decorator limit

I am currently writing a program using the decorator pattern. I am trying to find out how to limit the amount of decorators I can add to the first class. Such as:

Pizza plainPizza = new PlainPizza; Pizza sausage = new Sausage(plainPizza);

How could I code this where I can be limited to the amount of decorators I add on. Such as if I try to add this on top of the previous code:

Pizza pepperoni = new Pepperoni(sausage);

How can I prevent it from allowing pepperoni to be added/wrapped?

Thank you!

Designing a model to schedule classes for Students

I stuck with designing the following scenario. A new student joined in college and he needs to enroll in classes. Each Class has scheduled frequency that tells when to attend. A class may schedule for every 4 hours in a day or just once in a day. Now i have to implement a system to tell professors when a student should receive classes and i need to model a schedule for classes which handles start, end dates and frequencies.

What does "invalid new-expression of abstract class type 'class name' " mean?

I am busy with an assignment and am forced t use the factory method design pattern to create iterators which iterate over a container but I keep getting the above error. The classes I have are as follows:

ConstinerIterator.h:

#include "Object.h"

class ContainerIterator : public Object
{
public:
    void print(ostream& os);
    virtual Object* getFromIndex(int i) = 0;
protected:
    int compareTo(Object& obj);
};

DALIterator.h

#include "ContainerIterator.h"

class DALIterator : public ContainerIterator
{
public:
    DALIterator(Object** array)
    {
        this->array = array;
    }
    Object* getFromIndex(int i)
    {
        return array[i];
    }

private:
    Object** array;
};

ListAsArray.h:

#include "List.h"

class ListAsArray: public List
{
public:
    virtual ContainerIterator* createIterator() = 0;
};

DynamicArrayList.h

#include "ListAsArray.h"
#include "ArrayFactory.h"

class DynamicArrayList: public ListAsArray
{
public:
    DynamicArrayList()
    {
        array = new Object*[10];
    }
    ContainerIterator* createIterator()
    {
        IteratorFactory* factory = new ArrayFactory();
        return factory->factoryMethod(array);
    }

private:
    Object** array;
};

IteratorFactory.h

#include "Object.h"
#include "ContainerIterator.h"

class IteratorFactory : public Object
{
public:
    void print(ostream& os);
    virtual ContainerIterator* factoryMethod(Object** array) = 0;
protected:
    int compareTo(Object& obj);
};

ArrayFactory.h

#include "IteratorFactory.h"
#include "DALIterator.h"

class ArrayFactory : public IteratorFactory
{
public:
    ContainerIterator* factoryMethod(Object** array)
    {
        return new DALIterator(array);
    }
};

main.cpp:

#include <iostream>
#include "DynamicArrayList.h"
using namespace std;
int main()
{
    DynamicArrayList* dal = new DynamicArrayList();
    ContainerIterator* ci = dal->createIterator();

    return 0;
}

The error I get is:

ArrayFactory.h: In member function ‘virtual ContainerIterator* ArrayFactory::factoryMethod(Object**)’:
ArrayFactory.h:16:31: error: invalid new-expression of abstract class type ‘DALIterator’
   return new DALIterator(array);
                               ^
In file included from ArrayFactory.h:9:0,
                 from DynamicArrayList.h:5,
                 from DynamicArrayList.cpp:5:
DALIterator.h:10:7: note:   because the following virtual functions are pure within ‘DALIterator’:
 class DALIterator : public ContainerIterator

Thanks in advance for any help and apologies for the length of the question.