Changing the type of an object at some point in its life

I have the following hierarchy: Party is a base class extended by Person and Corporation. I need to change the class of an entity object at some point in his life, and I don't know what is the best way to do this.

I am modeling the financial world, so I have a party that can own shares in the corporation, and only the Corporation can have shareholders. Something like that:

class Party {
    public Set getShares();
}

class Corporation extends Party {
    public Set getShareholders();
    public void setShareholders(Party ss);

}

class Person extends Party {
    ... (some method still unknown)
}

I build objects that read data from the source, and it may happen that at first I only know the name of the participant, but I don’t know if it is a Person or a Corporation. But I need to create an object, so I create a common batch. After that, it may happen that I find out more information, so my party was a Corporation. So, I need to change the class that represents this object from the Party to the Corporation. So far, I decided to build a new object by copying old data into it. But I am not satisfied with this, and I am wondering what is the best way, template or something else, to realize what I would like to achieve.

I was thinking about the State Pattern , but I think it is best suited for other situations.

, . , . , , setShareholders Person, , , , , , , , , .

+3
6

, . , . , , setShareholders Person, , , , , , , , , .

, . "" E, " [] , Person". - E "" / Person ( , E).

: OP , :

:

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * Utilities to support using dynamic proxies
 */
public class DynamicProxy {

    /**
     * An invocation handler that passes calls to its delegate. This class
     * could be subclassed to provide dynamic method invocation handling
     * while still being able to fall back to the delegate object methods.
     *
     * @see InvocationHandler
     */
    public static class DelegatingInvocationHandler
    implements InvocationHandler {

        /** The object this proxy is wrapping */
        private final Object delegate;

        /**
         * Creates a delegate invocation handler around an object
         *
         * @param object
         *            The object to wrap
         */
        public DelegatingInvocationHandler(final Object delegate) {
            this.delegate = delegate;
        }

        /* (non-Javadoc)
         *
         * @see java.lang.reflect.InvocationHandler#invoke(java.lang.Object,
         * java.lang.reflect.Method, java.lang.Object[])
         */
        @Override
        public Object invoke(final Object proxy, final Method m,
                final Object[] args) throws Throwable {
            Object result;

            try {
                result = m.invoke(delegate, args);
            } catch (final InvocationTargetException e) {
                throw e.getTargetException();
            } catch (final Exception e) {
                throw new RuntimeException("unexpected invocation exception: "
                        + e.getMessage());
            }

            return result;
        }
    }

    /**
     * Create a dynamic proxy that implements only a specified subset of the
     * original object implemented interfaces. The proxy allows you to
     * essentially hide the other interfaces implemented by the original
     * object.
     *
     * @param delegate
     *            the object that the proxy "proxies" for (a.k.a. the delegate
     *            that handles the calls the proxy "allows" through)
     * @param requiredInterface
     *            one of the interfaces of the delegate that the proxy exposes
     * @param moreInterfaces
     *            any additional interfaces of the delegate to expose
     * @return the proxy
     *             a proxy for the delegate that can be cast to any of the
     *             specified interfaces
     */
    public static <T> T createSelectiveProxy(final T delegate,
            final Class<T> requiredInterface,
            final Class<?>... moreInterfaces) {
        if (delegate == null) {
            throw new IllegalArgumentException(
                    "The delegate object cannot be null");
        }

        return createProxy(new DelegatingInvocationHandler(delegate),
                requiredInterface, moreInterfaces);
    }

    /**
     * Creates a proxy using the specified invocation handler.
     *
     * @param object
     *            the implementing object that proxy wraps
     * @param invocationHandler
     *            the interfaces
     * @param moreInterfaces
     *            the interfaces
     * @return the object
     */
    @SuppressWarnings("unchecked")
    public static <T> T createProxy(final InvocationHandler invocationHandler,
            final Class<T> requiredInterface,
            final Class<?>... moreInterfaces) {
        if (invocationHandler == null) {
            throw new IllegalArgumentException(
                    "The invocation handler cannot be null");
        }

        final int size = (moreInterfaces != null ? moreInterfaces.length : 0);
        final Class<?>[] interfaces = new Class<?>[size + 1];
        interfaces[0] = requiredInterface;
        System.arraycopy(moreInterfaces, 0, interfaces, 1, moreInterfaces.length);

        return (T) Proxy.newProxyInstance(invocationHandler.getClass()
                .getClassLoader(), interfaces, invocationHandler);
    }
}

:

public class DynamicProxyDemo {

    private interface A {
        void methodA();
    }

    private interface B {
        void methodB();
    }

    private static class Foo implements A, B {

        public void methodA() {
            System.out.println("A");
        }

        public void methodB() {
            System.out.println("B");
        }
    }

    private DynamicProxyDemo() {}

    public static void main(final String[] args) {
        final Foo foo = new Foo(); // implements both interfaces

        // calls foo methods, but only A methods
        final A a = DynamicProxy.createSelectiveProxy(foo, A.class);

        // calls foo methods, but only B methods
        final B b = DynamicProxy.createSelectiveProxy(foo, B.class);

        // calls foo methods, but A and B methods
        final A ab = DynamicProxy.createSelectiveProxy(foo, A.class, B.class);

        System.out.println("\n *** Call a method A.methodA() on proxy 'a'");
        a.methodA();

        try {
            System.out.println("\n *** Call a method B.methodB() on proxy 'a' (throws exception)");
            ((B) a).methodB();
        } catch (final Exception ex) {
            ex.printStackTrace(System.out);
        }

        System.out.println("\n *** Call a method B.methodB() on proxy 'b'");
        b.methodB();

        try {
            System.out.println("\n *** Call a method A.methodA() on proxy 'b' (throws exception)");
            ((A) b).methodA();
        } catch (final Exception ex) {
            ex.printStackTrace(System.out);
        }

        System.out.println("\n *** Call a method A.methodA() on proxy 'ab'");
        ab.methodA();

        System.out.println("\n *** Call a method B.methodB() on proxy 'ab'");
        ((B) ab).methodB();

        // ClassCastException: $Proxy0 cannot be cast to DynamicProxy$Foo
        try {
            System.out.println("\n *** Call a method 'A' of class 'Foo' on proxy 'a' (throws exception)");
            ((Foo) a).methodA();
        } catch (final Exception ex) {
            ex.printStackTrace(System.out);
        }

        // ClassCastException: $Proxy1 cannot be cast to DynamicProxy$Foo
        try {
            System.out.println("\n *** Call a method 'B' of class 'Foo' on proxy 'b' (throws exception)");
            ((Foo) b).methodB();
        } catch (final Exception ex) {
            ex.printStackTrace(System.out);
        }

        // ClassCastException: $Proxy0 cannot be cast to DynamicProxy$B
        try {
            System.out.println("\n *** Call a method B.methodB() on proxy 'a' (throws exception)");
            ((B) a).methodB();
        } catch (final Exception ex) {
            ex.printStackTrace(System.out);
        }

        // ClassCastException: $DynamicProxy1 cannot be cast to DynamicProxy$A
        try {
            System.out.println("\n *** Call a method A.methodA() on proxy 'b' (throws exception)");
            ((A) b).methodA();
        } catch (final Exception ex) {
            ex.printStackTrace(System.out);
        }
    }
}

Run:

 *** Call a method A.methodA() on proxy 'a'
A

 *** Call a method B.methodB() on proxy 'a' (throws exception)
java.lang.ClassCastException: net.bertfernandez.reflection.$Proxy0 cannot be cast to net.bertfernandez.reflection.DynamicProxyDemo$B
    at net.bertfernandez.reflection.DynamicProxyDemo.main(DynamicProxyDemo.java:49)

 *** Call a method B.methodB() on proxy 'b'
B

 *** Call a method A.methodA() on proxy 'b' (throws exception)
java.lang.ClassCastException: net.bertfernandez.reflection.$Proxy1 cannot be cast to net.bertfernandez.reflection.DynamicProxyDemo$A
    at net.bertfernandez.reflection.DynamicProxyDemo.main(DynamicProxyDemo.java:59)

 *** Call a method A.methodA() on proxy 'ab'
A

 *** Call a method B.methodB() on proxy 'ab'
B

 *** Call a method 'A' of class 'Foo' on proxy 'a' (throws exception)
java.lang.ClassCastException: net.bertfernandez.reflection.$Proxy0 cannot be cast to net.bertfernandez.reflection.DynamicProxyDemo$Foo
    at net.bertfernandez.reflection.DynamicProxyDemo.main(DynamicProxyDemo.java:73)

 *** Call a method 'B' of class 'Foo' on proxy 'b' (throws exception)
java.lang.ClassCastException: net.bertfernandez.reflection.$Proxy1 cannot be cast to net.bertfernandez.reflection.DynamicProxyDemo$Foo
    at net.bertfernandez.reflection.DynamicProxyDemo.main(DynamicProxyDemo.java:81)

 *** Call a method B.methodB() on proxy 'a' (throws exception)
java.lang.ClassCastException: net.bertfernandez.reflection.$Proxy0 cannot be cast to net.bertfernandez.reflection.DynamicProxyDemo$B
    at net.bertfernandez.reflection.DynamicProxyDemo.main(DynamicProxyDemo.java:89)

 *** Call a method A.methodA() on proxy 'b' (throws exception)
java.lang.ClassCastException: net.bertfernandez.reflection.$Proxy1 cannot be cast to net.bertfernandez.reflection.DynamicProxyDemo$A
    at net.bertfernandez.reflection.DynamicProxyDemo.main(DynamicProxyDemo.java:97)
+2

, . , "", . .
, , . , Java ( , ) , . , .
- . , , . .
, Base 4 , Derived - 7 .
, (1 = 1 ): BASEBASEOTHERDERIVED. , Derived. : BASEDERIVEDERDERIVED. , "OTHER" . : BASEDERIVEDOTHERDERIVED. OTHER DERIVED, , , , . , : BASE____OTHERDERIVEDDERIVED, _____ - , .

0

. , :

, . , , . , . , .

, , , , . Builder, , .

Blackboard. , , , Blackboard , Person Corporion.

.

0

java.lang.Object . , , , , , . JavaScript. Java, .

, : Person Corporation. , :

class Party {
    PartyKind kind;
    Map<String, Property<?>> properties;

    public Property getProperty(String name) {
        return properties.get(name);
    }
}

class Property<T> {
    T value;
}

enum PartyKind {
    PERSON,
    CORPORATION
}

EDIT:, Property<T>, .

0

- , , .

Java-, Wikipedia , .

0

, .

, . . , .

:

abstract class Party {
    protected String nameOfParty;
    private Set<String> shares=new HashSet<String>();
    public Party(String name) {
        nameOfParty=name;
    }
    public Set<String> getShares(){
        return shares;
    }
    public void addShare(Party corp) {
         shares.add(((Corp)corp).nameOfParty);//only add corporation share.
    }
}

:

public class Corp extends Party {
    private Set<String> shareHolders = new HashSet<String>();

    public Corp(String name) {
        super(name);
    }

    public Corp(Party per) {
        super(per.nameOfParty);
    }

    public Set<String> getShareholders() {
        return shareHolders;
    }

    public void addShareholder(Party shareHolder) {
        this.shareHolders.add(shareHolder.nameOfParty);
    }

    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("Name Of Corp : ").append(nameOfParty);
        sb.append("\nShare's: ").append(this.getShares());
        sb.append("\nShare Holder : ").append(shareHolders);
        return sb.toString();
    }

}

:

public class Person extends Party {

    public Person(String name) {
        super(name);
    }

    public Person(Party name) {
        super(name.nameOfParty);
    }

    public void unknowMethod() {

    }

    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("Name Of Person : ").append(nameOfParty);
        sb.append("\nShare's: ").append(this.getShares());
        return sb.toString();
    }

}

:

public class Test {
    public static void main(String[] args) {
    /*
     * Initially consider all party to be person 
     * or create party with anonymous class if party information
     * is not available at that time of creation.
     */
        Party google = new Party("Google") {}; //Party with anonymous class
        Party yahoo = new Person("Yahoo");
        Party george = new Person("George");
        Party ali = new Person("Ali");
        Set<Party> list = new HashSet<Party>();

        list.add(google);
        list.add(yahoo);
        list.add(george);
        list.add(ali);
        // later came to know that google and yahoo are corporation's
        google = changeToCorp(list, google);
        yahoo = changeToCorp(list, yahoo);

        for (Party pty : list) {
            if (pty instanceof Person) {
                Person p = (Person) pty;
                p.unknowMethod();// access method of person
                p.addShare(yahoo);
                p.addShare(google);
                /*p.addShare(ali); 
                  will throw exception since ali is a person and cannot be added as share*/
                System.out.println("\n" + pty);
            }
            if (pty instanceof Corp) {
                Corp c = (Corp) pty;
                c.addShareholder(george);// access method of corp
                c.addShareholder(yahoo);
                c.addShare(google);
                c.addShareholder(ali);// share holder can be either a person or a corporation
                System.out.println("\n" + pty);
            }
        }

    }

    static Corp changeToCorp(Set<Party> se, Party per) {
        se.remove(per);
        Corp p = new Corp(per);
        se.add(p);
        return p;
    }

}
0

Source: https://habr.com/ru/post/1768981/


All Articles