- 추상 팩토리 패턴 (Abstract facotory pattern)

   다양한 구성 요소 별로 '객체의 집합'을 생성해야 할 때 유용하다.

( # 출처 : 위키 백과 https://ko.wikipedia.org/wiki/%EC%B6%94%EC%83%81_%ED%8C%A9%ED%86%A0%EB%A6%AC_%ED%8C%A8%ED%84%B4 )


- 추상화 팩토리 패턴 구현 예제

(#  전체소스 코드 : https://github.com/HelloPlutoKid/JAVADesignPattern/tree/master/AbstractFactoryPattern)

 

     조립 컴퓨터 판매 회사를 추상화 팩토리 패턴으로 구현.

     간단한 예제임으로 컴퓨터 부품은 CPU , GPU , Memory만 고려함.

 

    컴퓨터의 부품이 되는 부분을 구현 후, 컴퓨터를 만든다.

 

     부품 종류

     CPU 종류 : High CPU , Mid CPU , LOW CPU

     GPU 종류 : useGPU , notUseGPU,

     Memoery 종류 : 4GB , 8GB, 16GB

 

          

     컴퓨터 종류 

     ComputerA 스펙 : Mid Cpu, notUseGpu, SixTeenGB

     ComputerB 스펙 : High Cpu, UseGpu, EightGB

     ComputerC 스펙 : Low Cpu, notUseGpu, FourGB

 

예시. 컴퓨터 A


1. CPU, GPU, Memory 구성 부품 만들기

 

예를 들어서, High Cpu를 보면, Interface ICpu를 HighCpu에서 인터페이스를 구현한다.

package Inter;

/**
 * ICpu
 */
public interface ICpu {

    public void cpuInfo();
}
package cpu;

import Inter.ICpu;

/**
 * HighCpu
 */
public class HighCpu implements ICpu{

    @Override
    public void cpuInfo() {
        System.out.println("High performance CPU");
    }
}

 

 

 

2. 컴퓨터 리스트 만들기

예를 들어서, ComputerA를 보면, Interface IComputerFactory를 ComputerA에서 인터페이스를 구현한다.

package Inter;

/**
 * IPlayer
 */
public interface IComputerFactory {

        public ICpu cpu();
        public IGpu gpu();
        public IMemory memory();

}
import Inter.IComputerFactory;
import Inter.ICpu;
import Inter.IGpu;
import Inter.IMemory;
import cpu.MidCpu;
import gpu.notUseGpu;
import memory.SixTeenGB;

/**
 * ComputerA
 */
public class ComputerA implements IComputerFactory{

	@Override
	public ICpu cpu() {
		return new MidCpu();
	}

	@Override
	public IGpu gpu() {
		return new notUseGpu();
	}

	@Override
	public IMemory memory() {
		return new SixTeenGB();
	}

    
}

3. 메인 부분

import Inter.IComputerFactory;
import Inter.ICpu;
import Inter.IGpu;
import Inter.IMemory;
import computerList.ComputerA;
import computerList.ComputerB;
import computerList.ComputerC;

public class Main {
    public static void main(String[] args) {
        
        IComputerFactory computer = new ComputerA();
        ICpu cpu = computer.cpu();
        IGpu gpu = computer.gpu();
        IMemory memory = computer.memory();

        System.out.println("=======================");
        System.out.println("COMPUTER A SPEC");
        cpu.cpuInfo();
        gpu.gpuInfo();
        memory.memoryInfo();
        System.out.println("=======================");

        computer = new ComputerB();
        cpu = computer.cpu();
        gpu = computer.gpu();
        memory = computer.memory();

        System.out.println("=======================");
        System.out.println("COMPUTER B SPEC");
        cpu.cpuInfo();
        gpu.gpuInfo();
        memory.memoryInfo();
        System.out.println("=======================");

        computer = new ComputerC();
        cpu = computer.cpu();
        gpu = computer.gpu();
        memory = computer.memory();

        System.out.println("=======================");
        System.out.println("COMPUTER C SPEC");
        cpu.cpuInfo();
        gpu.gpuInfo();
        memory.memoryInfo();
        System.out.println("=======================");

    }
}

4. 결과화면


'[java] > [디자인패턴]' 카테고리의 다른 글

[Java] Builder 패턴  (0) 2019.12.24
블로그 이미지

미나미나미

,

# 부록 : 자바 zip 만들기 https://minaminaworld.tistory.com/131

 

[Java] 자바 zip 파일 만들기( 파일 , 폴더 압축하기)

부록 : zip 압축 풀기. [Java] 자바 zip 압축 풀기 ( 파일 , 폴더 압축 풀기) # 자바로 zip 파일 압축 풀기. - 폴더 안에 파일과, 하위 폴더 압축해버리기. - 아래의 ZIP 파일 압축 풀기. # UnZip.java - ZIP 파일..

minaminaworld.tistory.com


# 자바로 zip 파일 압축 풀기.

 

    - 폴더 안에 파일과, 하위 폴더 압축해버리기. 

 

    - 아래의 ZIP 파일 압축 풀기.

 

 


# UnZip.java - ZIP 파일 압축 풀기

package zipUtil;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class UnZip {
	/**
	 * 압축풀기 메소드
	 * 
	 * @param zipFileName 압축파일
	 * @param directory   압축 풀 폴더
	 */
	public boolean unZip(String zipPath, String zipFileName, String zipUnzipPath) {

		// 파일 정상적으로 압축이 해제가 되어는가.
		boolean isChk = false;

		// 해제할 홀더 위치를 재조정
		zipUnzipPath = zipUnzipPath + zipFileName.replace(".zip", "");

		// zip 파일
		File zipFile = new File(zipPath + zipFileName);

		FileInputStream fis = null;
		ZipInputStream zis = null;
		ZipEntry zipentry = null;

		try {
			// zipFileName을 통해서 폴더 만들기
			if (makeFolder(zipUnzipPath)) {
				System.out.println("폴더를 생성했습니다");
			}

			// 파일 스트림
			fis = new FileInputStream(zipFile);

			// Zip 파일 스트림
			zis = new ZipInputStream(fis, Charset.forName("EUC-KR"));

			// 압축되어 있는 ZIP 파일의 목록 조회
			while ((zipentry = zis.getNextEntry()) != null) {
				String filename = zipentry.getName();
				System.out.println("filename(zipentry.getName()) => " + filename);
				File file = new File(zipUnzipPath, filename);

				// entiry가 폴더면 폴더 생성
				if (zipentry.isDirectory()) {
					System.out.println("zipentry가 디렉토리입니다.");
					file.mkdirs();
				} else {
					// 파일이면 파일 만들기
					System.out.println("zipentry가 파일입니다.");
					try {
						createFile(file, zis);
					} catch (Throwable e) {
						e.printStackTrace();
					}
				}
			}
			isChk = true;
		} catch (Exception e) {
			isChk = false;
		} finally {
			if (zis != null) {
				try {
					zis.close();
				} catch (IOException e) {
				}
			}
			if (fis != null) {
				try {
					fis.close();
				} catch (IOException e) {
				}
			}
		}
		return isChk;
	}

	/**
	 * @param folder - 생성할 폴더 경로와 이름
	 */
	private boolean makeFolder(String folder) {
		if (folder.length() < 0) {
			return false;
		}

		String path = folder; // 폴더 경로
		File Folder = new File(path);

		// 해당 디렉토리가 없을경우 디렉토리를 생성합니다.
		if (!Folder.exists()) {
			try {
				Folder.mkdir(); // 폴더 생성합니다.
				System.out.println("폴더가 생성되었습니다.");
			} catch (Exception e) {
				e.getStackTrace();
			}
		} else {
			System.out.println("이미 폴더가 생성되어 있습니다.");
		}
		return true;
	}

	/**
	 * 파일 만들기 메소드
	 * 
	 * @param file 파일
	 * @param zis  Zip스트림
	 */
	private void createFile(File file, ZipInputStream zis) throws Throwable {

		// 디렉토리 확인
		File parentDir = new File(file.getParent());
		// 디렉토리가 없으면 생성하자
		if (!parentDir.exists()) {
			parentDir.mkdirs();
		}
		FileOutputStream fos = null;
		// 파일 스트림 선언
		try {

			fos = new FileOutputStream(file);
			byte[] buffer = new byte[256];
			int size = 0;
			// Zip스트림으로부터 byte뽑아내기
			while ((size = zis.read(buffer)) > 0) {
				// byte로 파일 만들기
				fos.write(buffer, 0, size);
			}
		} catch (Throwable e) {
			throw e;
		} finally {
			if (fos != null) {
				try {
					fos.close();
				} catch (IOException e) {
				}

			}

		}

	}
}

 

 

# Main.java - ZIP 파일 압축 풀기

package Main;

//import zipUtil.CompressZip;
import zipUtil.UnZip;

/**
 * Main
 */
public class Main {
	public static void main(String[] args) {

		// 압축 파일 위치와 압축된 파일
		 String zipPath = "G:/ZIP_TEST/";
		 String zipFile = "jsmpeg-player-master.zip";

		// 압축을 해제할 위치, 압축할 파일이름
		String unZipPath = "G:/ZIP_TEST/TEST/";
		String unZipFile = "jsmpeg-player";

		System.out.println("--------- 압축 해제 ---------");
		UnZip unZip = new UnZip();
		
		// 압축 해제 
		if (!unZip.unZip(zipPath, zipFile, unZipPath)) {
			System.out.println("압축 해제 실패");
		}

//		System.out.println("--------- 압축 하기 ---------");
//		CompressZip compressZip = new CompressZip();
//
//		// 압축 하기
//		try {
//			if (!compressZip.compress("G:/ZIP_TEST/TEST/jsmpeg-player-master", unZipPath, unZipFile)) {
//				System.out.println("압축 실패");
//			}
//		} catch (Throwable e) {
//			e.printStackTrace();
//		}
	}
}

# 결과화면

블로그 이미지

미나미나미

,

부록 : zip 압축 풀기.

 

[Java] 자바 zip 압축 풀기 ( 파일 , 폴더 압축 풀기)

# 자바로 zip 파일 압축 풀기. - 폴더 안에 파일과, 하위 폴더 압축해버리기. - 아래의 ZIP 파일 압축 풀기. # UnZip.java - ZIP 파일 압축 풀기 package zipUtil; import java.io.File; import java.io.FileInp..

minaminaworld.tistory.com


# 자바로 파일 , 폴더 zip로 압축하기 

 

    - 폴더 안에 파일과, 하위 폴더 압축해버리기. 

 

    - 아래의 폴더의 위치를 압축하겠습니다.

 


# CompressZip.java - ZIP 파일을 만들 유틸 

package zipUtil;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class CompressZip {
	/**
	 * @description 압축 메소드 
	 * @param path 압축할 폴더 경로
	 * @param outputFileName 출력파일명
	 */
	public boolean compress(String path, String outputPath, String outputFileName) throws Throwable {
		// 파일 압축 성공 여부 
		boolean isChk = false;
		
		File file = new File(path);
		
		// 파일의 .zip이 없는 경우, .zip 을 붙여준다. 
		int pos = outputFileName.lastIndexOf(".") == -1 ? outputFileName.length() : outputFileName.lastIndexOf(".");
		
		// outputFileName .zip이 없는 경우 
		if (!outputFileName.substring(pos).equalsIgnoreCase(".zip")) {
			outputFileName += ".zip";
		}
		
		// 압축 경로 체크
		if (!file.exists()) {
			throw new Exception("Not File!");
		}
		
		// 출력 스트림
		FileOutputStream fos = null;
		// 압축 스트림
		ZipOutputStream zos = null;
		
		try {
			fos = new FileOutputStream(new File(outputPath + outputFileName));
			zos = new ZipOutputStream(fos);
			
			// 디렉토리 검색를 통한 하위 파일과 폴더 검색 
			searchDirectory(file, file.getPath(), zos);
			
			// 압축 성공.
			isChk = true;
		} catch (Throwable e) {
			throw e;
		} finally {
			if (zos != null)
				zos.close();
			if (fos != null)
				fos.close();
		}
		return isChk;
	}

	/**
	 * @description 디렉토리 탐색
	 * @param file 현재 파일
	 * @param root 루트 경로
	 * @param zos  압축 스트림
	 */
	private void searchDirectory(File file, String root, ZipOutputStream zos) throws Exception {
		// 지정된 파일이 디렉토리인지 파일인지 검색
		if (file.isDirectory()) {
			// 디렉토리일 경우 재탐색(재귀)
			File[] files = file.listFiles();
			for (File f : files) {
				System.out.println("file = > " + f);
				searchDirectory(f, root, zos);
			}
		} else {
			// 파일일 경우 압축을 한다.
			try {
				compressZip(file, root, zos);
			} catch (Throwable e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	/**
	 * @description압축 메소드 
	 * @param file
	 * @param root
	 * @param zos
	 * @throws Throwable
	 */
	private void compressZip(File file, String root, ZipOutputStream zos) throws Throwable {
		FileInputStream fis = null;
		try {
			String zipName = file.getPath().replace(root + "\\", "");
			// 파일을 읽어드림
			fis = new FileInputStream(file);
			// Zip엔트리 생성(한글 깨짐 버그)
			ZipEntry zipentry = new ZipEntry(zipName);
			// 스트림에 밀어넣기(자동 오픈)
			zos.putNextEntry(zipentry);
			int length = (int) file.length();
			byte[] buffer = new byte[length];
			// 스트림 읽어드리기
			fis.read(buffer, 0, length);
			// 스트림 작성
			zos.write(buffer, 0, length);
			// 스트림 닫기
			zos.closeEntry();

		} catch (Throwable e) {
			throw e;
		} finally {
			if (fis != null)
				fis.close();
		}
	}

}

 

 

 


# Main.java - ZIP 파일을 만들 유틸 

 

 

package Main;

import zipUtil.CompressZip;
//import zipUtil.UnZip;

/**
 * Main
 */
public class Main {
	public static void main(String[] args) {

		// 압축 파일 위치와 압축된 파일
		// String zipPath = "G:/ZIP_TEST/";
		// String zipFile = "jsmpeg-player-master.zip";

		// 압축을 해제할 위치, 압축할 파일이름
		String unZipPath = "G:/ZIP_TEST/TEST/";
		String unZipFile = "jsmpeg-player";

//		System.out.println("--------- 압축 해제 ---------");
//		UnZip unZip = new UnZip();
//		// 압축 해제 
//		if (!unZip.unZip(zipPath, zipFile, unZipPath)) {
//			System.out.println("압축 해제 실패");
//		}

		System.out.println("--------- 압축 하기 ---------");
		CompressZip compressZip = new CompressZip();

		// 압축 하기
		try {
			if (!compressZip.compress("G:/ZIP_TEST/TEST/jsmpeg-player-master", unZipPath, unZipFile)) {
				System.out.println("압축 실패");
			}
		} catch (Throwable e) {
			e.printStackTrace();
		}
	}
}

# 결과화면

블로그 이미지

미나미나미

,

파일 수정 날짜 알아오기


FileMain.java

public class FileMain {

    public static void main(String[] args) {
        FileUtil file = new FileUtil();
        
        file.fileModifyInfo("./TestingFile.txt");
    }
}

TestingFile.java - 읽을 파일


FileUtil.java

    /***
     * 파일 수정 날짜 알아오기
     * @param path - 파일 위치
     */
    public void fileModifyInfo(String path) {
        File file = new File(path);
        String formatted = "";
        BasicFileAttributes attrs = null;

        try {
            attrs = Files.readAttributes(file.toPath(), BasicFileAttributes.class);
            FileTime time = attrs.lastModifiedTime();

            String pattern = "yyyy-MM-dd";
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);

            formatted = simpleDateFormat.format(new Date(time.toMillis()));
            System.out.println("수정된날짜 : "+new Date(time.toMillis()));
            System.out.println("형식지정표현 수정된날짜 : " + formatted);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

결과화면

블로그 이미지

미나미나미

,

파일 생성 날짜


FileMain.java

public class FileMain {

    public static void main(String[] args) {
        FileUtil file = new FileUtil();
        
        file.fileCreatedInfo("./TestingFile.txt");
    }
}

FileUtil.java

/**
     * 파일 생성 날짜 알아오기
     * @param path - 파일 위치
     */
    public void fileCreatedInfo(String path) {
        File file = new File(path);
        String formatted = "";
        BasicFileAttributes attrs = null;

        try {
            attrs = Files.readAttributes(file.toPath(), BasicFileAttributes.class);
            FileTime time = attrs.creationTime();

            String pattern = "yyyy-MM-dd";
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);

            formatted = simpleDateFormat.format(new Date(time.toMillis()));
            
            System.out.println("생성날짜 : "+new Date(time.toMillis()));
            System.out.println("형식지정표현 생성날짜 : " + formatted);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

읽어올 파일

결과화면

블로그 이미지

미나미나미

,

날짜 요일 구하기


DateMain.java

public class DateMain {
    public static void main(String[] args) {
        DateUtil date = new DateUtil();
        date.getDayOfweek("20190616");
    }
}

DateUtil.java

/**
     * 날짜로 요일 구하기
     * @param date - 요일 구할 날짜
     */
    public void getDayOfweek(String date){
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
        String[] week = {"일","월","화","수","목","금","토"};
        Calendar cal = Calendar.getInstance();
        Date getDate;
		try {
			getDate = format.parse(date);
			cal.setTime(getDate);			
			int w = cal.get(Calendar.DAY_OF_WEEK)-1;
            System.out.println(date + "는 " + week[w] +"요일 입니다");
		} catch (ParseException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
    }

결과화면

'[java]' 카테고리의 다른 글

[Java]파일 수정날짜 알아오기  (0) 2019.06.16
[Java]파일 생성날짜 알아오기  (0) 2019.06.16
[Java]날짜 계산하기  (0) 2019.06.16
[java] 자바 날짜 비교하기  (0) 2019.06.16
[Java]오늘 날짜 와 시간 표현하기  (0) 2019.06.16
블로그 이미지

미나미나미

,

[Java]날짜 계산하기

[java] 2019. 6. 16. 03:04

자바 날짜 비교하기


DateMain.java

public class DateMain {
    public static void main(String[] args) {
        DateUtil date = new DateUtil();
        try {
            // 60초 후
            date.calcDate("20190616 000000", 0, 0, 0, 0, 0, 60);
            // 60초 전
            date.calcDate("20190616 000000", 0, 0, 0, 0, 0, -60);
            // 30분 후
            date.calcDate("20190616 000000", 0, 0, 0, 0, 30, 0);
            // 30분 후
            date.calcDate("20190616 000000", 0, 0, 0, 0, -30, 0);
            // 12시간 후
            date.calcDate("20190616 000000", 0, 0, 0, 12, 0, 0);
            // 12시간 전
            date.calcDate("20190616 000000", 0, 0, 0, -12, 0, 0);
            // 하루 후
            date.calcDate("20190616 000000", 0, 0, 1, 0, 0, 0);
            // 2개월 후
            date.calcDate("20190616 000000", 0, 2, 0, 0, 0, 0);
            // 1년 2개월 후 
            date.calcDate("20190616 000000", 1, 2, 0, 0, 0, 0);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

DateUtil.java

/**
     * @param date - 날짜
     * @param year - 더할 년도
     * @param month - 더할 월 
     * @param day - 더할 날
     * @param hour - 더할 시간
     * @param min - 더할 분
     * @param sec - 더할 초
     * @throws Exception
     */
    public void calcDate(String date, int year, int month, int day , int hour , int min , int sec) throws Exception  {
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd HHmmss");
 
        Calendar cal = Calendar.getInstance();
        Date challDate = format.parse(date);
        cal.setTime(challDate);
        //년 더하기
        cal.add(Calendar.YEAR, year);      
        //달 더하기
        cal.add(Calendar.MONTH, month);     
        //날 더하기
        cal.add(Calendar.DATE, day);      
        //시 더하기
        cal.add(Calendar.HOUR, hour);      
        //분 더하기
        cal.add(Calendar.MINUTE, min);      
        //초 더하기
        cal.add(Calendar.SECOND, sec);      
        
        System.out.println( "계산한 날짜 =>" +  format.format(cal.getTime()) );
    }

 


결과화면

블로그 이미지

미나미나미

,

[java] 자바 날짜 비교하기

 

DateMain.java

 

public class DateMain {
    public static void main(String[] args) {
        DateUtil date = new DateUtil();
        // 비교할날짜 , 시작날짜 , 끝날짜
        date.compareDate("20190331", "20190401", "20190631");
        date.compareDate("20190531", "20190401", "20190631");
        date.compareDate("20191201", "20190401", "20190631");
    }
}

DateUtil.java

 

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * DateUtil
 */
public class DateUtil {

    /**
     * 날짜 비교하기
     * @param challengeDate - 비교할날짜
     * @param startDate - 시작날짜
     * @param endDate - 끝날짜
     */
    public void compareDate(String challengeDate, String startDate, String endDate){
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        try {
            Date chall = dateFormat.parse(challengeDate);
            Date start = dateFormat.parse(startDate);
            Date end = dateFormat.parse(endDate);

            if(chall.getTime() < start.getTime()){
                System.out.println("시작날짜("+ startDate +") 보다 " + challengeDate +" 이전 날짜 입니다.");
            }else if((start.getTime() <= chall.getTime()) &&(chall.getTime() <= end.getTime())){
                System.out.println("시작날짜("+ startDate +") ~ "+"끝날짜("+ endDate +")" + challengeDate +" 사이에 있습니다.");
            }else{
                System.out.println("끝날짜("+ endDate +") 보다 " + challengeDate +" 이후 날짜 입니다.");
            }
        } catch (ParseException e) {
			e.printStackTrace();
		}
    }
}

결과화면

'[java]' 카테고리의 다른 글

[java]날짜 요일 구하기  (0) 2019.06.16
[Java]날짜 계산하기  (0) 2019.06.16
[Java]오늘 날짜 와 시간 표현하기  (0) 2019.06.16
[java] gson 파싱(parse) double형 Int형 문제  (2) 2019.01.02
[java] url로 json 값 가져오기.  (0) 2018.12.26
블로그 이미지

미나미나미

,