java设计模式应用
Posted 雪夜杀机
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java设计模式应用相关的知识,希望对你有一定的参考价值。
1、builder设计模式(邮件工具类)
public class EmailMessage { private Message message; private static final String FROM = "sender"; private static final String PASSWORD = "****"; private static Session session; static { Properties properties = new Properties(); // 连接协议 properties.setProperty("mail.transport.protocol", "smtp"); // 主机名 properties.setProperty("mail.smtp.host", "smtp.qq.com"); // 端口号 properties.put("mail.smtp.port",465); properties.setProperty("mail.smtp.auth", "true"); // 设置是否使用ssl安全连接 ---一般都使用 properties.setProperty("mail.smtp.ssl.enable", "true"); // 设置是否显示debug信息 true 会在控制台显示相关信息 properties.setProperty("mail.debug", "true"); session = Session.getInstance(properties); } public static void main(String[] args) throws MessagingException { new EmailMessage .MessageBuilder(EmailMessage.session) .sender(EmailMessage.FROM) .receiver("receiver") .subject("java发送邮件") .content("<h3>你好,Jack</h3><p>很高兴你给的我的回信,这给了我很多灵感。</p>","text/html;charset=utf-8") .builder().send(); } public void send() throws MessagingException { Transport transport = session.getTransport(); transport.connect(FROM,PASSWORD); transport.sendMessage(message,message.getAllRecipients()); transport.close(); } public EmailMessage(MessageBuilder builder) { this.message = builder.getMessage(); } public static class MessageBuilder{ private Message message; public MessageBuilder(Session session) { this.message = new MimeMessage(session); } public MessageBuilder sender(String sender) { try { this.message.setFrom(new InternetAddress(sender)); } catch (MessagingException e) { e.printStackTrace(); } return this; } public MessageBuilder receiver(String receiver) { try { message.setRecipient(Message.RecipientType.TO,new InternetAddress(receiver)); } catch (MessagingException e) { e.printStackTrace(); } return this; } public MessageBuilder receivers(List<String> receivers) { try { InternetAddress[] internetAddress = new InternetAddress[receivers.size()]; int i = 0; for (String receiver : receivers) { internetAddress[i] = new InternetAddress(receiver); i = i + 1; } message.setRecipients(Message.RecipientType.TO,internetAddress); } catch (MessagingException e) { e.printStackTrace(); } return this; } public MessageBuilder subject(String subject) { try { this.message.setSubject(subject); } catch (MessagingException e) { e.printStackTrace(); } return this; } public MessageBuilder content(String content,String contentType) { try { this.message.setContent(content,contentType); } catch (MessagingException e) { e.printStackTrace(); } return this; } public EmailMessage builder() { return new EmailMessage(this); } public Message getMessage() { return message; } } }
以上是关于java设计模式应用的主要内容,如果未能解决你的问题,请参考以下文章
Android Java:在 onCreateView() 中返回空视图的片段