利用接口实现动态的创建对象 (水果类的调用)

利用接口实现动态的创建对象 (水果类的调用)

利用接口实现动态的创建对象
创建4个类:苹果、香蕉、葡萄、园丁
在三种水果的构造方法中打印一句话。

以苹果类为例:

class apple
{
public apple()
{
System.out.println(―创建了一个苹果类的对象‖);
}
}

要求从控制台输入一个字符串,根据字符串的值来判断创建三种水果中哪个类的对象
类图如下:
在这里插入图片描述

代码如下(示例):

import java.util.Scanner;
public class Gardener {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Gardener g = new Gardener();
		g.creat();
	}
	public Fruit creat() {
		Fruit f= null;
		Scanner sc = new Scanner(System.in);
		String str= sc.next();
		if(str.equals("苹果")) {
			f=new Apple();
		}
		if(str.equals("梨")) {
			f=new Pear();
		}
		if(str.equals("桔子")) {
			f=new Orange();
		}
		return f;
		
	}

}


interface Fruit{
	
}
class Apple implements Fruit{
	Apple(){
		
		System.out.println("创建了一个苹果类的对象");
	}
}
class Pear implements Fruit{
	Pear(){
		
		System.out.println("创建了一个梨类的对象");
	}
}
class Orange implements Fruit{
	Orange(){
		
		System.out.println("创建了一个桔子类的对象");
	}
}


  • 2
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
实现远程调用动态代理接口类的方法如下: 1. 创建一个接口,其中定义需要远程调用的方法。 2. 创建一个远程调用实现类,该类实现接口中定义的方法。 3. 创建一个动态代理类,该类实现接口,并在方法执行时调用远程调用实现类的对应方法。 4. 在客户端程序中,使用动态代理类的实例来调用接口中的方法,实际上是调用了远程调用实现类的方法。 下面是一个实现远程调用动态代理接口类的示例代码: ```java // 接口类 public interface RemoteInterface { void remoteMethod(); } // 远程调用实现类 public class RemoteImpl implements RemoteInterface { @Override public void remoteMethod() { // 远程调用实现 } } // 动态代理类 public class RemoteProxy implements InvocationHandler { private Object target; public RemoteProxy(Object target) { this.target = target; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { // 远程调用实现类的方法 method.invoke(target, args); return null; } } // 客户端程序 public class Client { public static void main(String[] args) { RemoteImpl remoteImpl = new RemoteImpl(); RemoteInterface remoteInterface = (RemoteInterface) Proxy.newProxyInstance( RemoteImpl.class.getClassLoader(), RemoteImpl.class.getInterfaces(), new RemoteProxy(remoteImpl) ); remoteInterface.remoteMethod(); } } ``` 在上面的示例代码中,我们定义了一个接口 RemoteInterface,并在 RemoteImpl 类中实现了该接口中的方法。然后,我们创建了一个动态代理类 RemoteProxy,该类实现了 InvocationHandler 接口,并在 invoke 方法中调用了远程调用实现类 RemoteImpl 中对应的方法。最后,在客户端程序中,我们使用 Proxy.newProxyInstance 方法创建动态代理类的实例,并调用接口中的方法,实际上是调用了远程调用实现类的方法。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值