본문 바로가기
코리아 IT아카데미/android

20일차 | DI 개념

by Sharon kim 2022. 3. 16.

 

Base63Encoder

package com.example.blog.test;


import android.os.Build;

import androidx.annotation.RequiresApi;

import java.util.Base64;

public class Base64Encoder implements IEncoder {

//    @Override
//    public String encode(String message) {
//        return null;
//    }

    @Override
    @RequiresApi(api = Build.VERSION_CODES.O)
    public String encode(String message) {
        return Base64.getEncoder().encodeToString(message.getBytes());
    }
}

Encoder

package com.example.blog.test;

import java.net.URLEncoder;

public class Encoder {

    IEncoder iEncoder;

    public Encoder(IEncoder iEncoder) {
        this.iEncoder = iEncoder;
    }

    public String encode(String message) {
        return iEncoder.encode(message);
    }

}

IEncoder

package com.example.blog.test;

public interface IEncoder {

    String encode(String message);
}

MyEncoder

package com.example.blog.test;

public class MyEncoder implements IEncoder{

    @Override
    public String encode(String message) {
        return message + "?/username=10";
    }
}

UrlEncoder

package com.example.blog.test;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

public class UrlEncoder implements IEncoder {

    public String encode(String message) {
        try {
            return URLEncoder.encode(message, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }
    }
}

 

MainTest

package com.example.blog.test;

import android.os.Build;

import androidx.annotation.RequiresApi;

public class MainTest {

    @RequiresApi(api = Build.VERSION_CODES.O)
    public static void main(String[] args) {


        // 1 . encoding -->
        String url = "http://lalacoding.site/init/user";

//        Base64Encoder base64Encoder = new Base64Encoder();
//        String result1 = base64Encoder.encode(url);
//        System.out.println(result1);

//        UrlEncoder urlEncoder = new UrlEncoder();
//        String result2 = urlEncoder.encode(url);
//        System.out.println(result2);

        // 2. 다형성 이용
//        IEncoder iEncoder1 = new Base64Encoder();
//        IEncoder iEncoder2 = new UrlEncoder();
//        String result1 = iEncoder1.encode(url);
//        String result2 = iEncoder2.encode(url);

        // 스트래티지 패턴 -->

        // 높은 수준으로 클래스 설계 !!!
        // DI 개념을 추가
//        Encoder encoder = new Encoder(new Base64Encoder());
//        String result = encoder.encode(url);
//        System.out.println(result);

        Encoder encoder = new Encoder(new MyEncoder());
        String result = encoder.encode(url);
        System.out.println(result);

    }
}