Month: February 2018

Difference between Association,Aggregation,Composition and Inheritance

Posted on

via Difference between Association,Aggregation,Composition and Inheritance

Advertisements

Building ReactJS Example with Event Handling

Posted on

Here is another simple example of ReactJS in which bunch of CommentBox components has been created and wrapped into a Board layer which is also a React Component and therefore events are binding to Save & Edit button under CommentBox component.

Set of comments text is initialized in parent Component i.e Board and each comment text is getting rendered into CommentBox Component by iteration.

Here is complete code:-

                <!DOCTYPE html>
        <html>

        <head>
            <meta charset="utf-8">
            <meta name="viewport" content="width=device-width">
            <title></title>
        </head>

        <body>
            <div id="content"></div>
            <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
            <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
            <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
            <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.24.0/babel.js"></script>
            
            <script type="text/babel">

                class CommentBox extends React.Component{
                constructor(props){
                    super(props);
                    this.state = {
                    editable : false
                    };
                }

                save(event){
                    this.props.updateCommentText(this.refs.commentTxt.value,this.props.index);
                    this.setState({
                        editable:false
                    })
                }
                remove(){
                    this.props.removeCommentText(this.props.index);
                    
                }
                edit(){
                    this.setState({
                        editable:true
                    })
                }
                renderForm(){
                    return (
                    <div className="row">
                        <div><textArea ref="commentTxt" name="commentBox" defaultValue={this.props.children}></textArea></div>
                        <button type="button" className="btn btn-danger" onClick={this.save.bind(this)}>Save</button>
                    </div>
                    );
                }
                renderHtml(){  
                    return (
                        <div className="row">
                        <div>{this.props.children}</div>    
                        <button type="button" className="btn btn-danger" onClick={this.edit.bind(this)}>Edit</button>
                        <button type="button" className="btn btn-success" onClick={this.remove.bind(this)}>Remove</button>
                        </div>
                    );
                }

                render() {
                    if(this.state.editable){
                        return this.renderForm(this);
                    }else{
                        return this.renderHtml(this);
                    }
                }
                }

            class Board extends React.Component{
                constructor(props){
                    super(props);
                    this.state ={
                        comments:[
                            'Techical Comments',
                            'Wordpress Comments',
                            'Facebook Comments'
                        ]
                    }
                }
                updateComment(text,i){
                    console.log("Saving Comment..."+text+" index ["+i+"]")
                    var arr = this.state.comments;
                    arr[i] = text;
                    this.setState({comments:arr})
                }
                removeComment(i){
                    console.log("Removing Comment..." + "index ["+i+"]")
                    var arr = this.state.comments;
                    arr.splice(i,1);
                    console.log("After removing a record :"+arr)
                    this.setState({comments:arr});
                }    

                eachComment(text,i){
                    return (
                                <CommentBox key={i} index={i} updateCommentText={this.updateComment.bind(this)}  removeCommentText={this.removeComment.bind(this)}> {text}</CommentBox> 
                            );
                }

                render(){
                    return(
                        <div className="container-fluid">{
                        this.state.comments.map(this.eachComment.bind(this))
                        }
                        </div>
                    );
                }
            } 
            ReactDOM.render(
                <Board />
                , document.getElementById('content'))
            </script>
        </body>

        </html>

Building First ReactJS Example

Posted on Updated on

 

 

Below is sample example of ReactJS in which a counter variable is an increment or decrement by 1 on onClick event that is binding with a button.

Here is a complete example.

index.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title></title>
  </head>
  <body>
    <div id="content"></div>

    <script src="https://fb.me/react-0.14.7.js"></script>
    <script src="https://fb.me/react-dom-0.14.7.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.24/browser.min.js"></script>
    
    
    <script type="text/babel">

        class CounterValue extends React.Component{
        constructor(props){
            super(props);
            this.state = {
            counter : 0
            };
        }

        onIncrementClickHandler() {
            this.setState({counter:this.state.counter +1})
        }

        onDecrementClickHandler() {
            if(this.state.counter == 0 ){
                return;
            }else{
             this.setState({counter:this.state.counter -1})
            }
        }
        render() {
            return (
            <div>
                <input type="button" onClick={this.onIncrementClickHandler.bind(this)} value="Increment"/>
                <input type="button" onClick={this.onDecrementClickHandler.bind(this)} value="Declement"/>
                <div>Counter value is  : {this.state.counter}</div>
                </div>
            );
        }
        }

      ReactDOM.render(<CounterValue />, document.getElementById('content'))
    </script>
  </body>
</html>

Command Design Pattern

Posted on Updated on

Command pattern is a behavioral design pattern in which an object is used to encapsulate all information needed to perform an action or trigger an event at a later time.

  1.  Decouple the caller and receiver call so the caller doesn’t know about receiver or receiver doesn’t know about a caller, they are communicating with Command layer.
  2. Allows requests to be encapsulated as objects, thereby allowing clients to be parametrized with different requests.
  3. delegates a request to a command object instead of implementing a particular request directly.

Key Points:-

Client – creates a ConcreteCommand object and sets its receiver.
Invoker – Asks the command to carry out the request;
Command – it is performing as “tokens” that are created by one client that knows what need to be done and passed to another client that has the resources for doing it.
Receiver –  knows how to perform the operations;

Below is snippet code for Command Design Pattern.

Command.Java – Here, Command decouples the object that invokes the operation from the one that knows how to perform it

package com.design.db;

public interface Command {
    Task submit();
}

DBSaveCommand.Java

package com.design.db;

public class DBSaveCommand implements Command {

    private final Object toBeObject;
    private final Class<?> persistCollection;
    private Receiver receiver = new DBProcessor();

    public DBSaveCommand(Class<?> persistCollection, Object object) {
        this.persistCollection = persistCollection;
        this.toBeObject = object;
    }

    @Override
    public Task submit() {
        try {
            this.receiver.save(this.persistCollection, this.toBeObject);
        } catch (Exception e) {
            return () -> e.getMessage();
        }
        return () -> new String("Save");
    }
}


DBRemoveCommand.Java

package com.design.db;

public class DBRemoveCommand implements Command {

    private final Object toBeObject;
    private final Class<?> persistCollection;
    private Receiver receiver = new DBProcessor();

    public DBRemoveCommand(Class<?> persistCollection, Object object) {
        this.persistCollection = persistCollection;
        this.toBeObject = object;
    }

    @Override
    public Task submit() {
        try {
            this.receiver.remove(this.persistCollection, this.toBeObject);
        } catch (Exception e) {
            return () -> e.getMessage();
        }
        return () -> new String("Delete");
    }
}


DBFetchByIdCommand.Java

package com.design.db;

public class DBFetchByIdCommand implements Command {

    private final Long toBeObject;
    private final Class<?> persistCollection;
    private Receiver receiver = new DBProcessor();

    public DBFetchByIdCommand(Class<?> persistCollection, Long object) {
        this.persistCollection = persistCollection;
        this.toBeObject = object;
    }

    @Override
    public Task submit() {
        try {
            return () -> this.receiver.fetchById(this.persistCollection, this.toBeObject);
        } catch (Exception e) {
            return () -> e.getMessage();
        }
    }
}

DBFetchAllCommand.Java

package com.design.db;

public class DBFetchAllCommand implements Command {
    private final Class<?> persistCollection;
    private Receiver receiver = new DBProcessor();

    public DBFetchAllCommand(Class<?> persistCollection) {
        this.persistCollection = persistCollection;
    }

    @Override
    public Task submit() {
        try {
            return () -> this.receiver.fetchAll(this.persistCollection);
        } catch (Exception e) {
            return () -> e.getMessage();
        }
    }
}

Receiver.Java

package com.design.db;

import java.util.Collection;

public interface Receiver {

    void save(Class<?> persistCollection, Object object);

    void remove(Class<?> persistCollection, Object object);

    Object fetchById(Class<?> persistCollection, Long id);

    Collection<?> fetchAll(Class<?> persistCollection);
}



DBRequestProcessor.Java – All the operation are perform here and only Command knows about the receiver and invokes the method of a receiver that is passed on through parameters.

package com.design.db;

import java.util.Collection;
import java.util.Collections;

public class DBRequestProcessor implements Receiver {


    @Override
    public void save(Class<?> persistCollection, Object object) {
        System.out.println("Entity Save");
    }

    @Override
    public void remove(Class<?> persistCollection, Object object) {
        System.out.println("Entity Removed");
    }

    @Override
    public Object fetchById(Class<?> persistCollection, Long id) {
        return id;
    }

    @Override
    public Collection fetchAll(Class<?> persistCollection) {
        return Collections.EMPTY_LIST;
    }
}

Invoker.Java

package com.design.db;

public interface Invoker {
    Task invoke(Command command);
}


DBCommandInvoker.Java – Invoker only know how to execute the Command and unknown about their concrete implementation of Command Interface.

package com.design.db;

public class DBCommandInvoker implements Invoker {


    public DBCommandInvoker() {
    }

    @Override
    public Task invoke(Command command) {
        return command.submit();
    }
}

Task.Java

package com.design.db;

public interface Task<T> {
    T get();
}


SqlRepository.Java :- This is Client here, which decides which command to be executed. to execute the Command, it passes to invoker object i.e DBCommandInvoker.

package com.design.db;

import java.util.Collection;

public class SqlRepository {

    private Invoker dbCommandInvoker = new DBCommandInvoker();

    public void save(Class zlass, Object payload) {
        dbCommandInvoker.invoke(new DBSaveCommand(zlass, payload));
    }

    public void remove(Class zlass, Long id) {
        dbCommandInvoker.invoke(new DBRemoveCommand(zlass, id));
    }

    public Object fetchById(Class zlass, Long id) {
        return dbCommandInvoker.invoke(new DBFetchByIdCommand(zlass, id)).get();
    }

    public Collection fetchAll(Class zclass) {
        return (Collection) dbCommandInvoker.invoke(new DBFetchAllCommand(zclass)).get();
    }
}