working on it ...

Filters

Explore Public Snippets

Sort by

Found 115 snippets matching: "design patterns"

    public by MarcoDeMagistris modified Apr 5, 2013  19134  47  6  -1

    Java: How to create a log4j Logger Manager using Singleton

    How to create a log4j Logger Manager using Singleton
    /**
    * LoggerManager class
    * This class implements log4j using Singleton
    */
    import org.apache.log4j.Logger;
    import org.apache.log4j.xml.DOMConfigurator;
    
    public class LoggerManager {
    	public enum LogLevel {DEBUG, INFO, WARNING, ERROR, FATAL};
    	private static LoggerManager obj;
    	private Logger oLog;
    	
    	private LoggerManager(){
    		/*
    		* Config.xml: file path used to configure log4j
    		*/
    		DOMConfigurator.configure("Config.xml");
    	}
    	
    	public LoggerManager(Logger logger) {
    		this();
    		setLogger(logger);
    	}
    
    	private void setLogger(Logger _oLog)
    	{
    		oLog = _oLog;
    	}
    	
    	public static LoggerManager getLogger(){
    		if (obj == null)
    			obj = new LoggerManager(Logger.getLogger(LoggerManager.class));
    		
    		return obj;
    	}
    	
    	public void Log(String _sMsg, LoggerManager.LogLevel _eLogLevel){
    		switch(_eLogLevel){
    			case DEBUG:
    				oLog.debug(_sMsg);
    				break;
    			case INFO:
    				oLog.info(_sMsg);
    				break;
    			case WARNING:
    				oLog.warn(_sMsg);
    				break;
    			case ERROR:
    				oLog.error(_sMsg);
    				break;
    			case FATAL:
    				oLog.fatal(_sMsg);
    				break;
    			default:
    				
    		}
    	}
    }
    
    /**
    * Main class
    * ex. Logger Manager example
    */
    public class Main {
    
    	public static void main(String[] args) {
    		LoggerManager.getLogger().Log("Starting Main", LoggerManager.LogLevel.INFO);
    	}
    
    }

    public by JKCPR modified Sep 20, 2016  8485  1  5  1

    AngularJS 'Ctrl as vm' pattern

    Within controller use 'var varname' if it is only needed internally, anything which needs to be bound to the ViewModel uses 'vm.varname' because in 'Controller as vm' pattern you forego using $scope to bind to the ViewModel and instead use the vm.object instead. Sometimes $scope is necessary but less so using this pattern....vm is readable and conv
    // AngularJS 'Controller As vm' pattern
    <script>
    (function(){
      "use strict";
    
      var app = angular.module('app')
        .controller('Customers', [function() {
          var vm = this; //this is implicitly bound to controller's scope
      
          vm.title = 'Customers';
          vm.customers = [
            {name: 'Haley'}, {name: 'Ella'}, {name: 'Landon'}, {name: 'John'}
            ];
        }])
        .controller('Shells', [function() {
          var vm = this; //this need not be named identically as in HTML
      
          vm.title = 'Shells';
          vm.shells = [
            {name: 'Main Shells'}, {name:'Half Shells'},{name: 'Quarter Shells'}
          ];
        }]);
    })();
    </script>
    
    <div ng-controller="Shell as shellVm">
      <h1>{{  shellVm.title }}</h1>
      <article ng-controller="Customers as customersVm">
        <h2> {{ customersVm.title }} in </h2>
        <ul ng-repeat="c in customersVm.customers">
          <li>{{ c.name }}</li>
        </ul>
      </article>
    </div>

    public by MarcoDeMagistris modified Apr 5, 2013  2467  4  5  0

    My First Snippet: How to create a singleton in C#

    This is the first example of a snippet: - the title represents in few words which is the exact issue the snippet resolves; it can be something like the name of a method; - the description (this field) is an optional field where you can add interesting information regarding the snippet; something like the comment on the head of a method; - the c
    public class MyClass 
    { 
       private static MyClass s_current; 
       private static object s_objSync = new object(); 
    
       private MyClass() {} 
    
       public static MyClass Instance 
       { 
           get 
           { 
               if (s_current == null) 
               { 
                   lock (s_objSync) 
                   { 
                       if (s_current == null) 
                           s_current = new MyClass(); 
                   } 
               } 
               return s_current; 
           } 
       } 
    } 

    public by terryc modified Feb 17, 2013  2016  1  5  0

    Design pattern in Java: singleton

    Implementation of singleton design pattern in Java
    public class Singleton {
    	static Singleton _singleton;
    	
    	static { 
    		_singleton = new Singleton();
    	}
    	
    	private Singleton() {
    	}
    
    	/**
    	 * Retrieve the only instance available in this JVM
    	 */
    	public static Singleton get() { 
    		return _singleton;
    	}
    }

    public by snip2code modified Aug 13, 2017  117  0  3  1

    First Snippet: How to play with Snip2Code

    This is the first example of a snippet: - the title represents in few words which is the exact issue the snippet resolves; it can be something like the name of a method; - the description (this field) is an optional field where you can add interesting information regarding the snippet; something like the comment on the head of a method; - the c
    /* place here the actual content of your snippet. 
       It should be code or pseudo-code. 
       The less dependencies from external stuff, the better! */

    public by mike modified Feb 17, 2013  1371  1  5  -1

    A singleton implementation in Java

    Java code for singleton design pattern
    public class SingletonClass {
    	static SingletonClass singleton;
    	
    	static { 
    		singleton = new SingletonClass();
    	}
    	
    	private SingletonClass() {
    		//init here...
    	}
    
    	public static SingletonClass get() { 
    		return singleton;
    	}
    }

    external by nikuyoshi modified Jul 29, 2015  102  0  2  0

    【デザインパターン再入門】コードを動かしながら理解を促すなら「java-design-patterns」がオススメ ref: http://qiita.com/nikuyoshi/items/d79ce27c17b6d2078581

    【デザインパターン再入門】コードを動かしながら理解を促すなら「java-design-patterns」がオススメ ref: http://qiita.com/nikuyoshi/items/d79ce27c17b6d2078581: file0.txt
    git clone https://github.com/iluwatar/java-design-patterns.git
    cd java-design-patterns
    mvn eclipse:eclipse
    
    
    

    external by Christopher Demicoli modified May 8, 2016  22  0  2  0

    Sample Cache Aside Implementation in C# as a Generic Extension Method. Part of Blog: https://blog.cdemi.io/design-patterns-cache-aside-pattern/

    Sample Cache Aside Implementation in C# as a Generic Extension Method. Part of Blog: https://blog.cdemi.io/design-patterns-cache-aside-pattern/: CacheAside.cs
    private static ConcurrentDictionary<string, object> concurrentDictionary = new ConcurrentDictionary<string, object>();
    public static T CacheAside<T>(this ICacheManager cacheManager, Func<T> execute, TimeSpan? expiresIn, string key)
    {
        var cached = cacheManager.Get(key);
    
        if (EqualityComparer<T>.Default.Equals(cached, default(T)))
        {
            object lockOn = concurrentDictionary.GetOrAdd(key, new object());
    
            lock (lockOn)
            {
                cached = cacheManager.Get(key);
    
                if (EqualityComparer<T>.Default.Equals(cached, default(T)))
                {
                    var executed = execute();
    
                    if (expiresIn.HasValue)
                        cacheManager.Set(key, executed, expiresIn.Value);
                    else
                        cacheManager.Set(key, executed);
    
                    return executed;
                }
                else
                {
                    return cached;
                }
            }
        }
        else
        {
            return cached;
        }
    }
    
    

    external by Daniel Garcia modified Jun 2, 2015  209  0  3  0

    Styles for printing correctly the book "Learning JavaScript Design Patterns" by Addy Osmani

    Styles for printing correctly the book "Learning JavaScript Design Patterns" by Addy Osmani: essentialjsdesignpatterns.css
    /*
    Styles for printing correctly the book
    "Learning JavaScript Design Patterns" by Addy Osmani
    http://addyosmani.com/resources/essentialjsdesignpatterns/book/
    */
    
    @media print {
        /* resets */
        body {
            background: none;
        }
    
        ol > ol {
            padding-left: 0;
        }
    
        .container {
            width: 100%;
            margin: 0;
            max-width: 100%;
            padding: 0;
            box-shadow: none;
        }
    
        #contents-list {
            border: none;
            padding: 0;
        }
    
    
        /* hide some elements */
        #reviews,
        .twitter-tweet-button,
        .codecodecode,
        .toolbar {
            display: none;
        }
    
        /* page breaks */
        h1, h2 {
            page-break-before: always;
        }
    
        h1.booktitle, h2.booktitle, h2 + h2 {
            page-break-before: auto;
        }
    
        .syntaxhighlighter {
            page-break-inside: avoid;
        }
    
        /* other improvements */
        .syntaxhighlighter {
            font-size: 13px !important;
        }
    
        .alert-message {
            background-color: #ffffaa;
            padding: 10px;
            border: 2px solid #ffff00;
            text-align: justify;
        }
    
        p, li, td {
            text-align: justify;
        }
    }
    
    

    external by Bruno Paz modified Jun 27, 2015  127  0  2  0

    S.O.L.I.D principles #design-patterns

    S.O.L.I.D principles #design-patterns: S.O.L.I.D.md
    # S.O.L.I.D principles
    
    - [Single Responsibility Principle](#single-responsibility-principle)
    - [Open/Closed Principle](#openclosed-principle)
    - [Liskov Substitution Principle](#liskov-substitution-principle)
    - [Interface Segregation Principle](#interface-segregation-principle)
    - [Dependency Inversion Principle](#dependency-inversion-principle)
    
    ## Single Responsibility Principle
    
    A class or method should have no more than one responsibility. If it has more than one responsibility then use the relevant refactoring technique(s) to extract the functionality into its own class or method.
    
    ## Open/Closed Principle
    
    An object should be 'open to extension' but 'closed for modification'.
    
    Here is a class that violates this principle...
    
    ```ruby
    require 'json'
    
    class Report
      def body
        { :a => 'Anna', :b => 'Bob', :c => 'Chris' }
      end
    
      def print
        body.to_json
      end
    end
    ```
    
    ...it violates the principle because if we want to extend the class to report the data in a different format, we can't without modifying the source class.
    
    To fix this we can use dependency injection...
    
    ```ruby
    require 'json'
    
    class Report
      def body
        { :a => 'Anna', :b => 'Bob', :c => 'Chris' }
      end
    
      def print(formatter: JSONFormatter.new)
        formatter.format(body)
      end
    end
    
    report = Report.new
    report.print(formatter: XMLFormatter.new)
    ```
    
    ...notice we inject a specific class to handle the required formatting. 
    
    This means we can extend the class without modifying it.
    
    ## Liskov Substitution Principle
    
    This principle only applies to code that uses inheritance. The reason why is because the principle states a subtype must be substitutable/interchangeable for their base class.
    
    The benefit of this principle is that when code is interchangeable, it becomes more reusable.
    
    The following code violates this principle...
    
    ```ruby
    class Animal
      def walk
         # do some walking
      end
    end
    
    class Cat < Animal
      def run
        # do some cat style running
      end
    end
    ```
    
    ...it violates the principle because the subclass implements a `run` method that doesn't appear in the base class.
    
    The solution is based on the use of interfaces, but as Ruby doesn't implement interfaces or abstract classes we instead create empty methods for each part of the proposed interface. 
    
    ```ruby
    class Animal
      def walk
         # do some walking
      end
    
      def run
         raise NotImplementedError
      end
    end
    
    class Cat < Animal
      def run
        # do some cat style running
      end
    end
    ```
    
    ## Interface Segregation Principle
    
    If a class uses an interface, then that interface should only contain methods or properties used by its consumers. If the interface has too much functionality then any change to the interface will effect more consumers than it probably needs to (meaning more chance for errors to occur).
    
    Take a look at the following code...
    
    ```ruby
    class Car
      def open; end
      def start_engine; end
      def change_engine; end
    end
    
    class Driver
      def drive
        # use `Car.open` and `Car.start_engine`
      end
    end
    
    class Mechanic
      def do_stuff
        # use `Car.change_engine`
      end
    end
    ```
    
    ...this code violates the principle because the `Car` class has methods that are partially used by both `Driver` and `Mechanic`.
    
    To fix this we split our interface into two interfaces...
    
    ```ruby
    class Car
      def open; end
      def start_engine; end
    end
    
    class CarInternals
      def change_engine; end
    end
    
    class Driver
      def drive
        # use `Car.open` and `Car.start_engine`
      end
    end
    
    class Mechanic
      def do_stuff
        # use `CarInternals.change_engine`
      end
    end
    ```
    
    ## Dependency Inversion Principle
    
    Objects should depend on abstractions. If they do so then the implementation of the abstractions can be changed without safely without affecting the code consuming the abstractions.
    
    One way to conform to this principle is to use "dependency injection", which we saw this used in the solution for OCP (Open/Closed Principle).
    
    Dependency Injection is one part of the solution. See this example: https://gist.github.com/Integralist/5763515 and you'll notice that DIP relies on the use of Interfaces (or in Ruby's case "duck typing") to decouple the consuming code and the injected dependency (e.g. using an Interface allows any object that implements that interface to be injected into the consuming object).
    
    
    • Public Snippets
    • Channels Snippets