1. 程式人生 > 其它 >學習筆記:C#入門(四)迴圈練習--用for迴圈寫三角形

學習筆記:C#入門(四)迴圈練習--用for迴圈寫三角形

技術標籤:設計模式

1.靜態代理(缺點:如果有多少個被代理類的話就得有多少個代理類)

代理模式必備條件:(1)一個介面,(2)一個被代理類,(3)一個代理類
被代理類和代理類都得實現同一個介面

(1)一個介面

//建立一個介面,讓被代理類去實現
public interface HelloInterface {
    void say();
}

(2)一個被代理類

//被代理類
public class Hello implements HelloInterface {
    @Override
    public void say() {
        System.out.println
("Hello,我是被代理類中的C"); } }

(3)一個代理類(靜態)

被代理類對代理類裡面的內容可以進行修改

//靜態代理
public class HelloProxy implements HelloInterface {
    HelloInterface helloInterface=new Hello();//多型
    @Override
    public void say() {
        System.out.println("Hello,我是代理類中的A");
        helloInterface.say(
); System.out.println("Hello,我是代理類中的B"); } }

執行結果為:
在這裡插入圖片描述

2.動態代理

動態代理只要修改上面的代理類就行

(3)一個代理類(動態)

動態代理類必須得實現 InvocationHandler


public class ProxyHandler implements InvocationHandler {

    private Object object;

    //建立一個函式,避免測試重複呼叫Proxy
    public Object createProxy(Object object){
        this
.object=object; //object.getClass() 放射的寫法 return Proxy.newProxyInstance(object.getClass().getClassLoader(), object.getClass().getInterfaces(),this); } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("Hello,我是動態代理類中的A"+method.getName()); method.invoke(object,args); System.out.println("Hello,我是動態代理類中的B"+method.getName()); return null; } } //測試 public static void main(String[] args) { HelloInterface helloInterface = new Hello(); ProxyHandler handler = new ProxyHandler(); HelloInterface helloInterface1= (HelloInterface) handler.createProxy(helloInterface); helloInterface1.say(); }

執行結果:
在這裡插入圖片描述
如果新來一個被代理類,只需新增一個介面,一個被代理類,然後將被代理類注入動態代理中即可,如:

//  newClass 新的被代理類
HelloInterface helloInterface1= (HelloInterface) handler.createProxy(new newClass);