Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-3 of 3 total  RSS 

Constructor overloading Java and PHP5

Java's constructor overload

class Hoge {

    public Hoge(){
        System.out.println("constructor 0");
    }

    public Hoge(int a){
        System.out.println("constructor 1:" + a);
    }

    public Hoge(int a, String[] hoge){
        System.out.println("constructor 2:" + a + ":" + hoge);
    }

    public Hoge(A a, B b, C c){
        System.out.println("constructor 3:" + a + ":" + b + ":" + c);
    }
}


PHP5 code

class Hoge {

    public function __construct(){
        $num = func_num_args();
        $args = func_get_args();
        switch($num){
        case 0:
            $this->__call('__construct0', null);
            break;
        case 1:
            $this->__call('__construct1', $args);
            break;
        case 2:
            $this->__call('__construct2', $args);
            break;
        case 3:
            $this->__call('__construct3', $args);
            break;
        default:
            throw new Exception();
        }
    }

    public function __construct0(){
        echo "constructor 0" . PHP_EOL;
    }

    public function __construct1($a){
        echo "constructor 1: " . $a . PHP_EOL;
    }

    public function __construct2($a, array $hoge){
        echo "constructor 2: " . $a . PHP_EOL;
        var_dump($hoge);
    }

    public function __construct3(A $a, A $b, C $c){
        echo "constructor 3: " . PHP_EOL;
        var_dump($a, $b, $c);
    }

    private function __call($name, $arg){
        return call_user_func_array(array($this, $name), $arg);
    }
}


example(PHP5)

interface C {
    const C = __CLASS__;
}
class A {
    const A = __CLASS__;
    private $a = array(1, 2, 3);
}
class B extends A{
    const B = __CLASS__;
    private $b = array(1, 2, 3);
}
class D extends B implements C {
    const D = __CLASS__;
    private $c = array(1, 2, 3);
}

$a = new Hoge();
$b = new Hoge(1);
$c = new Hoge(777, array(1,2,3));
$d = new Hoge(new A(), new B(), new D());

Overload for Ruby

An module let you overload functions

# Example:
#
# class Test1
#   include Overload
# 
#   def foo
#     puts "foo # Original one"
#   end
# 
#   overload :foo, :foo_str, String do |str, x|
#     puts "foo_str(String str, x)"
#   end
# 
#   overload :foo, Integer do |i|
#     puts "foo(Integer i) # no specific name"
#   end
# end
module Overload

  def self.included(klass)
    class << klass
      include Overload::Feature
    end
  end

  def self.spec_to_cond(spec)
    code = "args.length == #{spec[0]}"
    spec[1..-1].each_with_index { |s, i|
      code << " && #{s.inspect} === args[#{i}]"
    }
    code
  end

  module Feature

    private

    def overload(method_id, *spec, &block)
      if spec[0].instance_of? Symbol
        specific_method_id = spec.shift
        define_method(specific_method_id, block) if block
        block = instance_method(specific_method_id)
      elsif block
        define_method(method_id, block)
        block = instance_method(method_id)
        remove_method(method_id)
      else
        raise "You must give a block or a name of existing method!"
      end

      spec.unshift(block.arity)
      add_method_to_dispatch_table(method_id, spec, block)

      update_dispatcher(method_id)
    end

    def add_method_to_dispatch_table(method_id, key, block)
      if !dispatch_table[method_id]
        dispatch_table[method_id] = Hash.new
      end
      dispatch_table[method_id][key] = block
    end

    def update_dispatcher(method_id)
      remove_method(method_id) if method_defined?(method_id)
      class_eval dispatcher_code(method_id), "#{method_id}_dispatcher", 0
    end

    def dispatcher_code(method_id)
      method_body = <<-EOS
        def #{method_id.to_s}(*args, &blk)
          dt = DispatchTable[#{method_id.inspect}]
      EOS

      sorted_dispatch_table_of(method_id).each_with_index do |(spec, block), i|
        method_body << <<-EOS
          #{(i==0) ? "if" : "elsif"} #{Overload::spec_to_cond(spec)}
            dt[#{spec.inspect}].bind(self).call(*args, &blk)
        EOS
      end

      method_body << <<-EOS
          else
            raise "Couldn't find method for #{method_id}(\#{args.inspect[1..-2]})"
          end
        end
      EOS
    end

    def sorted_dispatch_table_of(method_id)
      dispatch_table[method_id].sort do |a,b|
        a[0].length <=> b[0].length
      end
    end

    def dispatch_table
      const_set("DispatchTable", Hash.new) if !const_defined?("DispatchTable")
      const_get("DispatchTable")
    end

  end

end

Function Overloader //JavaScript Class


This class allows javascript functions to be overloaded.

[UPDATED CODE AND HELP CAN BE FOUND HERE]




Usage:

myFunction = new Overloader;

myFunction.overload(function(x){
	document.write("Receives: NUMBER<br />");
}, Number);

myFunction.overload(function(x){
	document.write("Receives: STRING<br />");
}, String);

myFunction.overload(function(x,y){
	document.write("Receives: FUNCTION, NUMBER<br />");
}, Function, Number);

myFunction.overload(function(x,y){
	document.write("Receives: NUMBER, STRING<br />");
}, Number, String);

//test...
myFunction(function(){}, 123); //function + number version
myFunction(123); //number version
myFunction("ABC"); //string version
myFunction(123, "ABC"); //number + string version
myFunction({}); /*There's no Object version, so the function will choose the one that has more arguments in common and if there isnt a "best match", it will use the first function that was overloaded...*/



Here's the code

//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com/classes/overloader [v1.0]

Overloader = function(){ //v1.0
	var f = function(args){
		var i, h = "#";
		for(i in args = [].slice.call(arguments))
			h += args[i].constructor;
		if(!(h = f._methods[h])){
			var x, j, k, m = -1;
			for(i in f._methods){
				for(j in args.length > (k = 0, x = f._methods[i][1]).length ? x : args)
					(args[j] instanceof x[j] || args[j].constructor == x[j]) && ++k;
				k > m && (h = f._methods[i], m = k);
			}
		}
		return h ? h[0].apply(f, args) : undefined;
	};
	f._methods = {};
	f.overload = function(f, args){
		this._methods["#" + (args = [].slice.call(arguments, 1)).join("")] = [f, args];
	};
	f.unoverload = function(args){
		return delete this._methods["#" + [].slice.call(arguments).join("")];
	};
	return f;
};
« Newer Snippets
Older Snippets »
Showing 1-3 of 3 total  RSS