@@GetMapping을 사용한 페이지를 가져오기

1. 단순 페이지 불러오기

// localhost:8080/SimpleMapping1 으로 페이지 불러오기
    @GetMapping("SimpleMapping1")
    public String SimpleMapping1(){
        // views/SimpleMapping/SimpleMapping1.jsp 페이지
        return "SimpleMapping/SimpleMapping1";
    }

 


2. 페이지 숫자만 받기 / 영어문자로만 받기

    // localhost:8080/SimpleMapping1 으로 페이지 불러오기
    @GetMapping("/SimpleMapping2/{number:[1-9]+}")
    public String SimpleMapping2Number(@PathVariable String number){
        System.out.println("number = > " + number);
        // views/SimpleMapping/SimpleMapping1.jsp 페이지
        return "SimpleMapping/SimpleMapping1";
    }

    // localhost:8080/SimpleMapping1 으로 페이지 불러오기
    @GetMapping("/SimpleMapping2/{characters:[a-z]+}")
    public String SimpleMapping2String(@PathVariable String characters){
        System.out.println("characters = > " + characters);
        // views/SimpleMapping/SimpleMapping1.jsp 페이지
        return "SimpleMapping/SimpleMapping1";
    }

 2-1. 숫자로만 매핑 결과 

2-2. 영어로만 매핑 결과 


3. 페이지 요청 모든 패스 받기 / 한 패스만 받기 

    // "SimpleMapping3/"만 맞는 다면, 모든 다 받는다(ex: "test/123" , "test" , "test/1111/1123123")
    @GetMapping("/SimpleMapping3/**")
    @ResponseBody
    public String SimpleMapping3Multi(HttpServletRequest request){
        System.out.println("SimpleMapping3Multi");
        System.out.println("request.getRequestURI() = > " + request.getRequestURI());
        return "SimpleMapping3Multi " + request.getRequestURI();
    }

    // "SimpleMapping3/" 아래의 한 패스만 받는다, (ex: "test" , "zzzzz" , "1123123")
    @GetMapping("/SimpleMapping3/*")
    @ResponseBody
    public String SimpleMapping3Simple(HttpServletRequest request){
        System.out.println("SimpleMapping3Simple");
        System.out.println("request.getRequestURI() = > " + request.getRequestURI());
        return "SimpleMapping3Simple " + request.getRequestURI();
    }

3 - 1. 모든 패스 받기

 3 - 2. 한 패스 받기 

 

블로그 이미지

미나미나미

,

[Spring 에러] intellij release version 5/11/12 not supported

 

 

1. File - project structure - Project에서 사용할 자바 버전 체크 및 확인

2. File - Settings - Build, Execution, Deployment - Java Compiler에서 자바 컴파일 확인 

3. pom.xml에 "org.apache.maven.plugins"를 추가 

 

<build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <source>12</source>
                    <target>12</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

 

블로그 이미지

미나미나미

,

1. AOP(Aspect Orient Programing)

 

   - 객체 지향 소프트웨어 개발에서 횡단 관심사 또는 크로스커팅 관심사(cross-cutting concerns)는 다른 관심사에 영향을 미치는 프로그램의 애스펙트이다.

   - 요구 사항에 대해 핵심 관심사항과 횡단 관심사항으로 분할, 개발, 통합하여 모듈화를 극대화하는 프로그램 기법

  

=> 결국, 횡단 관심 요소들의 처리를 모듈화를 통한 효율적으로 극복

 


2. AOP의 구성요소

    - 핵심 관심 : 시스템의 핵심 가치와 목적이 드러난 관심 영역

    - 횡단 관심 : 쉽게 분리된 모듈로 작성하기 힘든 요구 사항, 공통 모듈 

    - Joint Point : 합류 지점, 메소드 실행시점 

    - Pointcut : 어디에 적용할 것인가, 계좌이체, 입출금, 이자 계산 적용대상  

    - Aspect : 모듈 

    - Advice : 해야할일 


3.  AOP 해보기(Spring Boot 사용)

   - 패키지 목록 

 

   3-1. pom.xml에 aop 요소

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>

 

 3-2. Aop 적용할 커스텀 어노테이션 생성(AopAnnotation.java)

import java.lang.annotation.*;

/**
 * 커스텀 어노테이션<br/>
 * Documented : javadoc으로 문서 생성 시 현재 어노테이션 설명 추가 <br/>
 * Retention : 어노테이션을 유지하는 정책 설정<br/>
 * Target : 어노테이션 적용 위치
 */
@Documented
@Retention(RetentionPolicy.CLASS)
@Target(ElementType.METHOD)
public @interface AopAnnotation {
}

 

3-3. 테스트할 서비스(클래스) 작성(AopService.java)

import org.springframework.stereotype.Service;

@Service
public class AopService {

    @AopAnnotation
    public void print(){
        System.out.println("Aop Service print문 실행");
    }

    @AopAnnotation
    public int returnIntValue(){
        System.out.println("returnIntValue 에서 값 10 return 합니다");
        return 10;
    }
}

 

3-4. AOP 클래스 생성(AopClass.java)

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

@Component
@Aspect
public class AopClass {

    @Around("@annotation(AopAnnotation)")
    public Object aopTest(ProceedingJoinPoint proceedingJoinPoint) throws Throwable{
        System.out.println("AopClass aopTest @Around @annotation(AopAnnotation) 동작");
        Object resultValue = proceedingJoinPoint.proceed();
        System.out.println("resultValue = > " + resultValue);
        return resultValue;
    }

    @Around("@annotation(AopAnnotation)")
    public Object aopTest2(ProceedingJoinPoint proceedingJoinPoint) throws Throwable{
        System.out.println("AopClass aopTest2 @Around @annotation(AopAnnotation) 동작");
        Object resultValue = proceedingJoinPoint.proceed();
        return resultValue;
    }
}

 

3-5. AppRunner 작성 (AppRunner.java)

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

@Component
public class AppRunner implements ApplicationRunner {

    @Autowired
    AopService aopService;


    @Override
    public void run(ApplicationArguments args) throws Exception {
        aopService.print();
        aopService.returnIntValue();
    }
}

4. 결과화면 

블로그 이미지

미나미나미

,

 

1. Spring Validataion Annotation 종류

    # hibernate 공식 문서 :  http://hibernate.org/validator/

    # hibernate annotation 종류 : https://docs.jboss.org/hibernate/stable/validator/reference/en-US/html_single/#section-builtin-constraints

 

The Bean Validation reference implementation. - Hibernate Validator

Express validation rules in a standardized way using annotation-based constraints and benefit from transparent integration with a wide variety of frameworks.

hibernate.org

2. pom.xml에 hibernate 의존성 추가

 <dependency>
            <groupId>org.hibernate.validator</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>6.0.8.Final</version>
        </dependency>

3. VO 생성하기

package VO;

import javax.validation.constraints.*;

public class JoinVO {

    // 길이 지정
    @Size(min = 5 , max = 20 , message = "5 - 20 사이에 글자")
    private String id;

    // 길이 지정
    @Size(min = 5 , max = 20 , message = "5 - 20 사이에 글자")
    private String pw;

    // 0 - 99 구간 , 소수점 허용 안함
    @Digits(integer = 2, fraction = 0)
    @Min(0)
    @Max(99)
    private int age;

    // 이메일 형식 체크
    @Email(message = "이메일 형식에 맞게 넣으세요")
    private String email;

    private String information;

    private String hobby;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getPw() {
        return pw;
    }

    public void setPw(String pw) {
        this.pw = pw;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getInformation() {
        return information;
    }

    public void setInformation(String information) {
        this.information = information;
    }

    public String getHobby() {
        return hobby;
    }

    public void setHobby(String hobby) {
        this.hobby = hobby;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    @Override
    public String toString() {
        return "JoinVO{" +
                "id='" + id + '\'' +
                ", pw='" + pw + '\'' +
                ", age=" + age +
                ", email='" + email + '\'' +
                ", information='" + information + '\'' +
                ", hobby='" + hobby + '\'' +
                '}';
    }
}

4. controller - ValidController.java

package Controller;

import VO.JoinVO;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.validation.Valid;
import java.util.List;

@Controller
public class ValidController {

    /**
     * joinForm 불러오기
     * @param joinVO
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/JoinForm", method = RequestMethod.GET)
    public String boardRegisterForm(@ModelAttribute("joinVO") JoinVO joinVO, Model model) throws Exception {
        return "JoinForm";
    }

    /**
     * joinForm 내용 검증
     * @param joinVO
     * @param bindingResult
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/joinInsert", method = RequestMethod.POST)
    public String boardInsert(@Valid JoinVO joinVO, BindingResult bindingResult, Model model) throws Exception {
        // Form 정보 출력
        System.out.println(joinVO.toString());
        // Validation 결과의 에러의 목록 출력
        if(bindingResult.hasErrors()) {
            List<ObjectError> errors = bindingResult.getAllErrors();
            for(ObjectError error : errors){
                System.out.println(error.getDefaultMessage());
            }
            return "JoinForm";
        }

        return "redirect:/JoinForm";
    }
}

5. JSP 페이지 - JoinForm.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%--JSTL 문법 --%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%--form:form 태그 사용--%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<html>
<head>
    <title>가입하세요</title>
</head>
<body>
<h1>회원가입</h1>
<form:form modelAttribute="joinVO" action="/joinInsert" method="post">
<%--    <form:errors path="*" cssClass="error"/>--%>
    <table border="1">
        <tbody>
        <tr>
            <th>이름</th>
            <td>
                <form:input path="id" id="id" size="20" maxlength="20"/>
                <form:errors path="id" cssClass="error"/>
            </td>
        </tr>
        <tr>
            <th>비밀번호</th>
            <td>
                <form:password path="pw" id="pw" size="20" maxlength="20"/>
                <form:errors path="pw" cssClass="error"/>
            </td>
        </tr>
        <tr>
            <th>나이</th>
            <td>
                <form:input path="age" id="age" size="20" maxlength="20"/>
                <form:errors path="age" cssClass="error"/>
            </td>
        </tr>
        <tr>
            <th>이메일</th>
            <td>
                <form:input path="email" id="email" size="20" maxlength="20"/>
                <form:errors path="email" cssClass="error"/>
            </td>
        </tr>
        <tr>
            <th>내용</th>
            <td>
                <form:textarea path="information" id="content"/>
                <form:errors path="information" cssClass="error"/>
            </td>
        </tr>
        <tr>
            <td>취미</td>
            <td><form:select path="hobby">
                <form:option value="soccer" label="축구" />
                <form:option value="basketball" label="농구" />
                <form:option value="tennis" label="테니스" />
            </form:select></td>
        </tr>
        <tr>
            <td colspan="2"><input type="submit" value="등록"/></td>
        </tr>
        </tbody>
    </table>
</form:form>
</body>
</html>

6.결과화면 

   - 등록을 눌렀을 때, 타당하지 않은 이유를 표시함

블로그 이미지

미나미나미

,

 

1. 메인의 SchoolMember.name을 바꾸기

/**
 * Hello world!
 *
 */
public class App {
    public static void main( String[] args ){
        System.out.println("SchoolMember().MebmberName() = > " + new SchoolMember().MebmberName());
    }
}
public class SchoolMember {

    public String MebmberName() {
        return "abc";
    }
}

- 결과화면

2. 새로운 프로젝에 net.bytebuddy를 불러오기

# https://mvnrepository.com/artifact/net.bytebuddy/byte-buddy

    - 런타임시 java Class들을 동적으로 만들어낼 수 있는 라이브러리

 

Maven Repository: net.bytebuddy » byte-buddy

Byte Buddy is a Java library for creating Java classes at run time. This artifact is a build of Byte Buddy with all ASM dependencies repackaged into its own name space. VersionRepositoryUsagesDate1.10.x1.10.8Central385Feb, 20201.10.7Central25Jan, 20201.10.

mvnrepository.com


2. pom.xml 의존성 추가 (Junit은 필요없습니다.)

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
    <!-- https://mvnrepository.com/artifact/net.bytebuddy/byte-buddy -->
    <dependency>
      <groupId>net.bytebuddy</groupId>
      <artifactId>byte-buddy</artifactId>
      <version>1.10.8</version>
    </dependency>
  </dependencies>

3.  변경할 함수와 이름 만들어 주기

public class SchoolNameChange {
    // premain
    public static void premain(String agentArgs, Instrumentation inst) {

        new AgentBuilder.Default()
                .type(ElementMatchers.any())
                .transform(new AgentBuilder.Transformer() {
                    @Override
                    public DynamicType.Builder<?> transform(DynamicType.Builder<?> builder, TypeDescription typeDescription, ClassLoader classLoader, JavaModule module) {
                        return builder.method(named("memberName")).intercept(FixedValue.value("Test"));
                    }
                }).installOn(inst);
    }
}

4. pom.xml 의 빌드에 Maven jar 생성 부분 추가

<build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <version>3.2.0</version>
                <configuration>
                    <archive>
                        <index>true</index>
                        <manifest>
                            <addClasspath>true</addClasspath>
                        </manifest>
                        <manifestEntries>
                            <mode>development</mode>
                            <url>${project.url}</url>
                            <key>value</key>
                           <!-- Manifest attribute -->
                          <!-- 애플리케이션 시작시 옵션으로 주기, Package 넣어주기-->
                          <Premain-Class>org.example.SchoolNameChange</Premain-Class>
                          <!-- 클래스 변경 허용 부분 -->
                          <Can-Redefine-Classes>true</Can-Redefine-Classes>
                          <Can-Retransform-Classes>true</Can-Retransform-Classes>
                          <!-- 클래스 변경 허용 부분 -->
                          <!-- Manifest attribute -->
                    </archive>
                </configuration>
            </plugin>
        </plugins>
    </build>

5. mvn clean package , jar 파일 생성

 - tistory... .jar 파일 생성

6. 기존의 프로젝트에 VM options에 jar 파일 추가

 [-javaagent:C:\Users\.....\target\tistoryBytebuddyJavaagent-1.0-SNAPSHOT.jar]

 

7. 실행

블로그 이미지

미나미나미

,

- 빌더패턴(Builder Pattern)

(# github 예제 소스 : https://github.com/HelloPlutoKid/JAVADesignPattern/tree/master/2.Builder)

 

정의 : 복합 객체의 생성 과정과 표현 방법을 분리하여 동일한 생성 절차에서 서로 다른 표현 결과를 만들 수 있게 하는 패턴

(#위키 백과 : https://ko.wikipedia.org/wiki/%EB%B9%8C%EB%8D%94_%ED%8C%A8%ED%84%B4  

 

빌더 패턴을 사용하면, 생성자를 통한 변수 초기화를 빌더 패턴을 대신함으로써 여러 생성자를 생성할 필요가 없고, 생성자의 순서에 맞게 변수 내용을 작성할 필요성이 없습니다. 또한, 변수의 내용을 보다 직관적으로 초기화가 가능합니다.


빌더 패턴을 통한 음식을 만들어 보겠습니다.

 

Food와 FoodBuilder의 관계

     Food을 생성을 FoodBuider를 통해서 Food 객체 생성과 변수 초기화를 진행합니다.       

 

클래스 구조


1. Food.java

package food;

/**
 *  국수 음식 
 */
public class Food {
    private String source;
    private String meat;
    private String noodle;

    public Food(String source, String meat, String noodle){
        this.source = source;
        this.meat = meat;
        this.noodle = noodle;
    }

    /**
     * @param meat the meat to set
     */
    public void setMeat(String meat) {
        this.meat = meat;
    }

    /**
     * @param noodle the noodle to set
     */
    public void setNoodle(String noodle) {
        this.noodle = noodle;
    }

    /**
     * @param source the source to set
     */
    public void setSource(String source) {
        this.source = source;
    }

    /**
     * @return the meat
     */
    public String getMeat() {
        return meat;
    }
    
    /**
     * @return the noodle
     */
    public String getNoodle() {
        return noodle;
    }

    /**
     * @return the source
     */
    public String getSource() {
        return source;
    }

    @Override
    public String toString() {
        return "source = >" + source + "," + "noodle = >" + noodle + "," + "meat = >" + meat;
    }
    
}

2. FoodBuilder.java

package food;

public class FoodBuilder {
    private Food food;

    public FoodBuilder(){
        food = new Food("","","");
    }

    public FoodBuilder start(){
        return this;
    }
    public FoodBuilder setSource(String source){
        this.food.setSource(source);
        return this;
    }

    public FoodBuilder setMeat(String meat){
        this.food.setMeat(meat);
        return this;
    }

    public FoodBuilder setNoodle(String noodle){
        this.food.setNoodle(noodle);
        return this;
    }

    public Food build(){
        return this.food;
    }
}

 

 

 


3. Main.java

import food.Food;
import food.FoodBuilder;

/**
 * Main
 */
public class Main {

    public static void main(String[] args) {
    	// 모든 변수를 초기화 하는 경우 
        Food food1 = new FoodBuilder()
        		.start()
        		.setSource("라면스프")
        		.setNoodle("라면사리")
        		.setMeat("소고기")
        		.build();
        
        // meat를 제외한 변수를 초기화 하는 경우 
        Food food2 = new FoodBuilder()
        		.start()
        		.setSource("쌀스프")
        		.setNoodle("국수")
        		.build();

        System.out.println(food1.toString());
        System.out.println(food2.toString());

    }
}

4. 결과화면

 

블로그 이미지

미나미나미

,

[Java] Super()의 이해

[java] 2019. 12. 23. 14:48

[Java] Super()의 이해

- Super() 부모의 요소를 접근 하기 위해서 사용. 

  - 클래스 생성자 , public 변수,  public 함수의 접근이 가능함.


 

- ParentClass를 생성 후, ChildClass의 상속하는 구조.


1. Parent와 Child 클래스

ParentClass 클래스

package parent;

public class ParentClass {
	// private 요소 
	private String mother;
	private String father;
	// public 요소
	public String car = "BMW";
	
	// 빈 생성자 
	public ParentClass() {
		this.mother = "ParentMother";
		this.father = "ParentFather";
	}
	
	public ParentClass(String mother , String father) {
		this.mother = mother;
		this.father = father;
	}
	
	public String toString() {
		return "Parent = > " + this.father + " / " + "Parent = > " + this.mother; 
	}
	
	public String getFather() {
		return father;
	}
	
	public String getMother() {
		return mother;
	}
}

 

 

 

ChildClass 클래스

package child;

import parent.ParentClass;

public class ChildClass extends ParentClass {

	private String daughter;
	private String son;
	
	// 자식의 요소에만 값 할당, 부모의 요소는 접근하지 않음.
	public ChildClass(String daughter, String son) {
		this.daughter = daughter;
		this.son = son;
	}

	// 자식 요소와 부모 요소에 접근. 
	public ChildClass() {
		// 부모의 생성자를 호출하여 사용.
		super("ChildDaughter", "ChildSon");
		// 부모의 public 변수에 접근하여 값 변경
		super.car = "K7";
		
		// 자식의 요소의 값 할당 
		this.daughter = "not";
		this.son = "not";
	}

	public String toString() {
		return "Child = > " + super.getFather() + "/" + "Child = > " + super.getMother() + "/" + "Child = > "
				+ this.daughter + "/" + "Child = > " + this.son + "/" + "car = > " + super.car;
	}
}

2. Main Class

import child.ChildClass;

public class Main {

	public static void main(String[] args) {
		
		System.out.println("부모 Class 그대로 사용");
		ChildClass child1 = new ChildClass("Main1" , "Main2");
		System.out.println(child1.toString());
		
		System.out.println("부모 Class 초기화(Super()) 사용");
		ChildClass child2 = new ChildClass();
		System.out.println(child2.toString());		
	}

}

3. 결과화면

 

블로그 이미지

미나미나미

,

- 추상 팩토리 패턴 (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
블로그 이미지

미나미나미

,