说在前面:体验一把,小记一下。别回头打的连我妈都认不出来了,哈哈。
一位大师曾经说过:”人有分工不同,没有高低贵贱之分"。然而我觉得人生下来就分三六九等。
下面举个例子:一个初级程序员在公司做什么捏?
有什么构思呢?最起码的是可扩展吧,那就抽象出来,面向接口编程喽。
思路:
- Coder(接口)
- primaryCoder implements Coder(实现类)
- Work (接口)
- primaryWork implements Work(实现类)
基于java的demo(就是普通的撒)
//Coder.java
package test;
public interface Coder {
void coding();
}
//PrimaryCoder.java
package test;
public class PrimaryCoder implements Coder {
private Work work;
public PrimaryCoder(Work work) {
this.work = work;
}
@Override
public void coding() {
work.toDoing();
}
}
//Work.java
package test;
public interface Work {
void toDoing();
}
//Primary.java
package test;
public class PrimaryWork implements Work {
private String task;
public PrimaryWork(String task) {
this.task = task;
}
@Override
public void toDoing() {
System.out.println("write java about api...");
}
}
//Main.java
package test;
public class Main {
public static void main(String[] args) {
Work pw = new PrimaryWork("java");
Coder coder = new PrimaryCoder(pw);
coder.coding();
}
}
这个demo体会一下面向接口编程就好啦。
基于SpringBoot的demo(springboot搭架子容易啊)
所以先把架子搭起来,不然下面的代码演示不了。
//Coder.java
package com.sprint.learnBean;
public interface Coder {
void coding();
}
//PrimaryCoder.java
package com.sprint.learnBean;
public class PrimaryCoder implements Coder {
private Work work;
public PrimaryCoder(Work work) {
this.work = work;
}
@Override
public void coding() {
work.toDoing();
}
}
//Work.java
package com.sprint.learnBean;
public interface Work {
void toDoing();
}
//PrimaryWork.java
package com.sprint.learnBean;
import java.io.PrintStream;
public class PrimaryWork implements Work {
// private String task;
private PrintStream printStream;
/* public PrimaryWork(String task) {
this.task = task;
}
*/
public PrimaryWork(PrintStream printStream) {
this.printStream = printStream;
}
@Override
public void toDoing() {
System.out.println("write java about api...");
}
}
//Config.java
ackage com.sprint.learnBean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Bean;
@Configuration
public class Config {
@Bean
public Coder coderType(){
return new PrimaryCoder(primaryWork());
}
@Bean
public Work primaryWork() {
return new PrimaryWork(System.out);
}
}
//Main.java
package com.sprint.learnBean;
import org.springframework.web.bind.annotation.*;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
@RestController
public class Main {
@RequestMapping("/learnbean")
public String index() {
AnnotationConfigApplicationContext afc = new AnnotationConfigApplicationContext(Config.class);
Coder coder = afc.getBean(Coder.class);
coder.coding();
afc.close();
return "learnbean";
}
}
访问:http://localhost:8080/learnbean 控制台会打印write java about api...
重点来了:
感觉出有什么不同了吗?(用demo1 和 demo2来区分哈)
demo1 中Main.java 中必须先实例化一个PrimaryWork并通过上转型赋给Work。
demo2中然而并没有这么强耦合,通过@Bean产生对象并将其注入到IOC容器,依赖关系托付于IOC容器管理。
如题体验了一把,小记一下。欢迎拍砖。
参考资料:《spring in action》