Skip to content

Instantly share code, notes, and snippets.

@danilomo
Created June 8, 2018 11:17
Show Gist options
  • Save danilomo/b20c736f3f9bf811826bda468d730e9e to your computer and use it in GitHub Desktop.
Save danilomo/b20c736f3f9bf811826bda468d730e9e to your computer and use it in GitHub Desktop.
Example of decorator pattern
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.mycompany.teste;
import java.util.HashMap;
import java.util.Map;
/**
*
* @author danilo
*/
public class Decorator {
public static void main(String[] args) {
Func fib = new Timed(new Memoeized(new Fibonacci()), "fib" );
fib.apply(40);
fib.apply(40);
}
}
interface Func {
double apply(double x);
}
class Fibonacci implements Func {
@Override
public double apply(double x) {
return (double) fibonacci((int) x);
}
public long fibonacci(int n) {
if (n <= 1) {
return n;
} else {
return fibonacci(n - 1) + fibonacci(n - 2);
}
}
}
class Memoeized implements Func{
private Map<Double, Double> cache = new HashMap<>();
private Func func;
public Memoeized(Func func) {
this.func = func;
}
@Override
public double apply(double x) {
if (cache.containsKey(x)){
return cache.get(x);
}
double val = func.apply(x);
cache.put(x, val);
return val;
}
}
class Timed implements Func{
private Func func;
private String name;
public Timed(Func func, String name) {
this.func = func;
this.name = name;
}
@Override
public double apply(double x) {
long t1 = System.currentTimeMillis();
double val = func.apply(x);
long t2 = System.currentTimeMillis();
double diff = (t2 - t1) / 1000.0;
System.out.println("Time to finish " + name + ": " + diff );
return val;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment