直接上代碼
class Message {
private Channel channel ; // 保存消息發送通道
private String title ; // 消息標題
private String content ; // 消息內容
// 4、調用此構造實例化,此時的channel = 主類ch
public Message(Channel channel,String title,String content) {
this.channel = channel ; // 保存消息通道
this.title = title ;
this.content = content ;
}
public void send() {
// 6、判斷當前通道是否可用,那么此時的this.channel就是主類中的ch
if (this.channel.isConnect()) { // 如果連接成功
System.out.println("【消息發送】title = " + this.title + "、content = " + this.content) ;
} else { // 沒有連接
System.out.println("【ERROR】沒有可用的連接通道,無法進行消息發送。") ;
}
}
}
class Channel {
private Message message ; // 消息發送由Message負責
// 2、實例化Channel類對象,調用構造
public Channel(String title,String content) {
// 3、實例化Message,但是需要將主類中的ch傳遞到Message中、this = ch
this.message = new Message(this,title,content) ;
// 5、消息發送
this.message.send() ; // 發送消息
}
// 以后在進行方法創建的時候如果某一個方法的名稱以is開頭一般都返回boolean值
public boolean isConnect() { // 判斷連接是否創建,如果創建可以發送
return true ;
}
}
public class JavaDemo {
public static void main(String args[]) {
// 1、實例化一個Channel對象
@SuppressWarnings("unused")
Channel ch = new Channel("春節到了","大家新年快樂。") ; // 實例化Channel對象就表示要發送消息
}
}
?